Constructor assignment on prototypal inheritance
-
14-11-2019 - |
Question
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
- As
@GGG
&@CMS
have explained, the constructor alignment takes no effect on creating the child object bynew 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. WhileChild.prototype = new Parent(...)
includes parent's properties to child,Child.prototype = Object.create(Parent.prototype)
doesn't.
Solution
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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow