开发者

keeping the constructor correctly after inheritance

开发者 https://www.devze.com 2023-02-01 02:56 出处:网络
I\'ve noticed this interesting problem: function a() { this.aprop = 1; } function b() { this.bprop = 2; }

I've noticed this interesting problem:

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

As far as I know, x.constructor should be b, but it's actually a when b inherits from a through its prototype? Is there a way I can inherit from a without screwing up my constructor?


This is because b.prototype.constructor is assigned new a().constructor on the 3rd line. You can change this property back on the following line:

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

精彩评论

暂无评论...
验证码 换一张
取 消