Objektvererbung in JavaScript

Meine Frage bezieht sich auf ein untergeordnetes Objekt, das die Prototypkette seines übergeordneten Objekts beibehält.

In John Resigs Advanced Javascript Folien (http://ejohn.org/apps/learn/#76) Er schreibt, dass Sie ein neues übergeordnetes Objekt instanziieren müssen, um die Prototypkette eines untergeordneten Objekts aufrechtzuerhalten.

Durch ein paar schnelle Tests habe ich jedoch festgestellt, dass die Prototypenkette beibehalten wird, indem der Prototyp des untergeordneten Objekts dem Prototyp des übergeordneten Objekts gleichgesetzt wird.

Jede Klarstellung wäre sehr dankbar!

Ursprünglicher Code

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" );

Meine geänderte Version

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();

Antworten auf die Frage(2)

Ihre Antwort auf die Frage