2010-12-23 9 views
5

Ich habe dieses interessante Problem bemerkt:den Konstruktor korrekt nach Vererbung halten

function a() { this.aprop = 1; } 
function b() { this.bprop = 2; } 
b.prototype = new a(); // b inherits from a 
var x = new b(); // create new object with the b constructor 
assert(x.constructor == b); // false 
assert(x.constructor == a); // true 

Soweit ich weiß, sollte x.constructorb sein, aber es ist eigentlich a wenn b erbt von a durch seinen Prototyp? Gibt es einen Weg, den ich von a erben kann, ohne meinen Konstruktor zu vermasseln?

Antwort

3

Dies ist, weil b.prototype.constructor in der 3. Zeile new a().constructor zugeordnet ist. Sie können diese Eigenschaft wieder in der folgenden Zeile ändern:

function a() { this.aprop = 1; } 
function b() { this.bprop = 2; } 
b.prototype = new a(); // b inherits from a 
b.prototype.constructor = b; // <-- add this 
var x = new b(); // create new object with the b constructor 
assert(x.constructor == b); // false 
assert(x.constructor == a); // true 
+0

Vielen Dank! Wäre es möglich und eine gute Idee für mich, eine schnelle Funktion (Ziel, Eltern) zu schreiben, die diese beiden Zeilen ausführt? –

+0

@Delan: Sicher, das wäre möglich. –

+0

Das funktioniert perfekt; Danke nochmal Andy. –

Verwandte Themen