プロトタイプ継承にこのPro JavaScript Design Patternsのクローンメソッドを使用していますが、これは基本的にCrockford's object() functionと同じです。 (唯一の違いはクロックフォードは括弧を呼び出す追加していることですが、Fが空になったので、私はそれが重要なことはよく分からない。私は問題ないと思います。)プロトタイプ継承を使ったオーバーライドメソッド
clone = function(object) {
function F() {}
F.prototype = object;
return new F;
};
ので、この適用、私は2つのオブジェクトを作成しようとしますが、もう一方はメソッドを継承します。 1つはビューポート寸法用で、もう1つはデバイス寸法用です。しかし、両方とも同様の数学比較を使用するので、私はそれが他を継承することが理にかなっていると思う。 (。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'
私はViewport.width()
などにビューポートになどthis.width()
への参照を変更するとエラーが離れて行くが、その後I継承が機能しないと考えてください。いずれかのオブジェクトからメソッドを使用すると、エラーが発生します。私は何が欠けていますか?これにはより良いパターンがありますか?どうすればこの作品を作れますか?
[私の作品](のhttp:// jsfiddle。 net/VNAQa/5 /) – Raynos
@Raynos @AndréAlçadaPadez私はそれを理解しました。問題は、私が「this」の文脈を変えた方法でメソッドを使用していたことでした。メソッドは* this *で定義されていませんでした。 – ryanve