我的問題是關於維護其父對象的原型鏈的子對象。JavaScript中的對象繼承
在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();
[這](http://stackoverflow.com/questions/5991152/why-do-we-use-boy-prototype-new-human-to-simulate-inheritance)可能會幫助 – aaronman
在「現代」瀏覽器:'Ninja.prototype = Object.create(Person.prototype)'。 – elclanrs