2010-12-23 71 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