6

Professional JavaScript for Web Developers, Third Edition by Nicholas C. Zakas (Wrox, 2012, p.210-215) では、次の関数を使用した「寄生結合継承」について説明しています。

function inheritPrototype(subType, superType) {
    var prototype = object(superType.prototype); 
    prototype.constructor = subType; 
    subType.prototype = prototype; 
}

サブタイプのプロトタイプ.コンストラクターへの割り当てが何をするのか、または何をすべきかをまだ理解していません。何かが欠けていない限り、サンプル コードを使用して得られる出力は同じです。

inheritPrototype に「拡張オブジェクト」(prototype.constructor = subType;) がない場合: http://jsfiddle.net/Q22DN/

inheritPrototype の「拡張オブジェクト」(prototype.constructor = subType;) を使用 http://jsfiddle.net/eAYN8/

これは本当に目的のないコードの行でしょうか? 説明ありがとうございます!

4

2 に答える 2

2

デモ コンストラクター プロトタイプを上書きするため、SubType.prototype.constructor が失われます。後でオブジェクト コンストラクターを知りたい場合は、明示的に設定する必要があります...

function object(o){
    function F(){}
    F.prototype = o;
    return new F();
}

function inheritPrototype(subType, superType) {
    var prototype = object(superType.prototype); 
    prototype.constructor = subType; //if omit (new SubType()).constructor === superType 
    subType.prototype = prototype; 
}

function SuperType(name){
    this.name = name;
}

function SubType(name, age){
    SuperType.call(this, name);
    this.age = age;
}

inheritPrototype(subType, superType);
于 2013-06-05T00:49:30.347 に答える