我的问题是关于维护其父对象原型链的子对象。
在 John Resig 的高级 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();