Javascript 继承后正确保留构造函数

Javascript 继承后正确保留构造函数,javascript,Javascript,我注意到了一个有趣的问题: 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);

我注意到了一个有趣的问题:

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.constructor
应该是
b
,但当
b
通过原型从
a
继承时,它实际上是
a
?有没有一种方法可以从
a
继承而不破坏我的构造函数?

这是因为
b.prototype.constructor
在第三行分配了
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
函数a(){this.aprop=1;}
函数b(){this.bprop=2;}
b、 原型=新的a();//b继承自a

b、 prototype.constructor=b;//谢谢对我来说,写一个快速的
函数(target,parent)
来完成这两行是可能的,也是一个好主意吗?@Delan:当然,这是可能的。