obj.constructor returns top most constructor instead of the immediate parent constructor

StackOverflow https://stackoverflow.com/questions/20314529

  •  07-08-2022
  •  | 
  •  

سؤال

just ran into this little confusion while playing around with javascript inheritance.

 function A() {}

 function B() {}
 B.prototype = new A();

 function C() {}
 C.prototype = new B();

 var x = new C();
 x.construction // -> returns A in chrome console.

I was expecting x.constructor to be C (or even B maybe) but not all the way to A (why even stop at A and not show Object then)

هل كانت مفيدة؟

المحلول

When you replace the prototype object entirely, the original constructor reference is removed with the original prototype object and is instead inherited from the new A(), etc.

function B() {}

console.log(B.prototype.constructor === B); // true

B.prototype = new A();

console.log(B.prototype.constructor === B); // false
console.log(B.prototype.constructor === A); // true

So, you'll have to reset the constructor after setting the prototype:

function A() {}

function B() {}
B.prototype = new A();
B.prototype.constructor = B;

function C() {}
C.prototype = new B();
C.prototype.constructor = C;
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top