When making the prototypal inheritance, it's asked to refer the child's constructor back to itself below,
A = function() {}
B = function() {}
B.prototype = new A;
B.prototype.constructor = B;
What would take adverse effect if not?
EDIT
@GGG & @CMS have explained, the constructor alignment takes no
effect on creating the child object by new Child(...), but is
necessary to correctly reflect the child object's constructor later.@GGG has also suggested a defensive alternative to extend
the prototype chain. While Child.prototype = new Parent(...)
includes parent's properties to child, Child.prototype =
Object.create(Parent.prototype) doesn't.First, please don't do this:
B.prototype = new A;
Do this instead (shim Object.create for old browsers):
B.prototype = Object.create(A.prototype);
As for constructor, nothing will break if you don't do this, but if you don't:
A = function() {};
var a = new A();
console.log(a.constructor); // A
B = function() {};
var b = new B();
console.log(b.constructor); // A (!)
...setting the constructor property of the prototype back to the actual constructor function allows you to do this:
B.prototype.constructor = B;
var b = new B();
console.log(b.constructor); // B
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With