我使用这种克隆方法从Pro JavaScript Design Patterns进行原型继承,这与Crockford's object() function基本相同。 (唯一的区别是,克罗克福德增加调用括号,但由于F是空的,我不知道它的问题,我不认为这个问题。)用原型继承覆盖方法
clone = function(object) {
function F() {}
F.prototype = object;
return new F;
};
因此,应用此,我寻找两个对象,一个从另一个继承方法。一个用于视口尺寸,另一个用于设备尺寸。但都使用类似的数学比较,所以我认为有一个继承另一个是有道理的。 (More info about the actual methods is here)
var Viewport = {
inORout: function (curr, min, max) {
// [email protected] boolean true if curr equals min or max, or is in between.
min = min || 0; // Default min.
return !max ? (curr >= min) : (curr >= min && curr <= max);
}
, width: function() {
return document.documentElement.clientWidth;
}
, height: function() {
return document.documentElement.clientHeight;
}
, inWidthRange: function (min, max) {
return this.inORout(this.width(), min, max);
}
, inHeightRange: function (min, max) {
return this.inORout(this.height(), min, max);
}
};
// I want to use prototypal inheritance to make Device inherit the
// inORout/inWidthRange/inHeightRange methods from Viewport but
// override the width() and height() methods:
var Device = clone(Viewport);
Device.width = function() {
return window.screen.width;
};
Device.height = function() {
return window.screen.height;
};
但问题是,我得到的错误是这样的:
Object # <Object> has no method 'inORout'
and
Object # <Object> has no method 'width'
and
Object # <Object> has no method 'height'
如果我改变参考this.width()
等在视口中Viewport.width()
等项目的错误消失后来我认为继承不起作用。当我使用任一对象的方法时发生错误。我错过了什么?有更好的模式吗?我该如何做这项工作?
[对我的作品(HTTP://的jsfiddle。 net/VNAQa/5 /) – Raynos
@Raynos @AndréAlçadaPadez我想通了。问题是我以一种改变'this'的上下文的方式使用这些方法。这个方法没有在* this这个*上定义。 – ryanve