Proper save of constructor after inheritance

I noticed this interesting problem:

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

As far as I know, it x.constructorshould be b, but in fact a, when does it binherit from athrough its prototype? Is there a way I can inherit from awithout stuffing my constructor in?

+5
source share
1 answer

This is due to the fact that it b.prototype.constructoris assigned new a().constructoron the third line. You can change this property 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
+3
source

All Articles