私の質問は、親オブジェクトのプロトタイプ チェーンを維持する子オブジェクトに関するものです。
John Resig の Advanced Javascript スライド ( http://ejohn.org/apps/learn/#76 ) で、子オブジェクトのプロトタイプ チェーンを維持するには、新しい親オブジェクトをインスタンス化する必要があると書いています。
しかし、いくつかの簡単なテストを通じて、子オブジェクトのプロトタイプを親オブジェクトのプロトタイプと等しく設定するだけで、プロトタイプ チェーンが維持されることに気付きました。
説明をいただければ幸いです。
オリジナルコード
function Person(){}
Person.prototype.dance = function(){};
function Ninja(){}
// Achieve similar, but non-inheritable, results
Ninja.prototype = Person.prototype;
Ninja.prototype = { dance: Person.prototype.dance };
assert( (new Ninja()) instanceof Person, "Will fail with bad prototype chain." );
// Only this maintains the prototype chain
Ninja.prototype = new Person();
var ninja = new Ninja();
assert( ninja instanceof Ninja, "ninja receives functionality from the Ninja prototype" );
assert( ninja instanceof Person, "... and the Person prototype" );
assert( ninja instanceof Object, "... and the Object prototype" );
私の修正版
function Person(){}
Person.prototype.dance = function(){console.log("Dance")};
function Ninja(){}
// Achieve similar, but non-inheritable, results
Ninja.prototype = Person.prototype;
assert( (new Ninja()) instanceof Person, "Will fail with bad prototype chain." );
var ninja = new Ninja();
assert( ninja instanceof Ninja, "ninja receives functionality from the Ninja prototype" );
assert( ninja instanceof Person, "... and the Person prototype" );
assert( ninja instanceof Object, "... and the Object prototype" );
ninja.dance();