继承后正确保持构造函数

Del*_*ani 5 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); // true
Run Code Online (Sandbox Code Playgroud)

据我所知,x.constructor应该是b,但它实际上是ab继承a通过其原型?有没有一种方法可以继承a而不搞砸我的构造函数?

And*_*y E 3

这是因为在第三行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
Run Code Online (Sandbox Code Playgroud)