2

プロトタイプ継承にこの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継承が機能しないと考えてください。いずれかのオブジェクトからメソッドを使用すると、エラーが発生します。私は何が欠けていますか?これにはより良いパターンがありますか?どうすればこの作品を作れますか?

あなたは少し異なった事をしなければならないプロトタイプを持つ
+0

[私の作品](のhttp:// jsfiddle。 net/VNAQa/5 /) – Raynos

+0

@Raynos @AndréAlçadaPadez私はそれを理解しました。問題は、私が「this」の文脈を変えた方法でメソッドを使用していたことでした。メソッドは* this *で定義されていませんでした。 – ryanve

答えて

1

var Viewport = {}; 
Viewport.prototype.inOrOut = function(){...}; 
Viewport.prototype.width= function(){...}; 
Viewport.prototype.height = function(){...}; 

この方法、あなたは正しく継承することができるようになります...

+0

古典的な継承ではありませんか?とにかく試してみましたが、 'undefined'のinORout 'というプロパティを設定できませんでした。 'clone()'メソッドはそれを処理する必要があります。私はそれが 'Object.create'と同等だと信じています。https://developer.mozilla.org/ja/JavaScript/Reference/Global_Objects/Object/createはJavaScript 1.8.5で追加されました – ryanve

+0

function F(){} - >あなたはありませんそこに=(等号)がありませんか? –

+0

関数 'function F(){}'は 'var F = function(){};'と同等です。 – ryanve

関連する問題