2010-12-23 75 views
5

後,我發現這個有趣的問題:保持正確構造繼承

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 

據我所知,x.constructorb,但它實際上是a當從a通過其原型b繼承?有沒有一種方法,我可以從a繼承而不用搞砸我的構造函數?

回答

3

這是因爲b.prototype.constructor在第3行分配new a().constructor。您可以將此屬性重新更改爲以下行:

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

謝謝!對於我來說寫一個能夠完成這兩行的快速`函數(目標,父)`是一個好主意嗎? – 2010-12-23 11:23:45