There are 2 ways to call the parent constructor in the child.
var A = function A() {
this.x = 123;
};
var B = function B() {
// 1. call directly
A.call(this);
// 2. call from prototype
A.prototype.constructor.call(this);
};
B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;
Are there any situations when one would be safer/better than the other, or are they always equivalent?
There are 2 ways to call the parent constructor in the child.
var A = function A() {
this.x = 123;
};
var B = function B() {
// 1. call directly
A.call(this);
// 2. call from prototype
A.prototype.constructor.call(this);
};
B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;
Are there any situations when one would be safer/better than the other, or are they always equivalent?
Share Improve this question edited Sep 16, 2013 at 16:39 Ilia Choly asked Nov 7, 2012 at 14:46 Ilia CholyIlia Choly 18.6k14 gold badges94 silver badges164 bronze badges 7 | Show 2 more comments1 Answer
Reset to default 18It's always better to use the base constructor directly for the following reasons:
- It's faster. The interpreter doesn't need to access
prototype.constructor
. - It's safer. Consider the program below.
A
inherits from C
, but I forgot to set A.prototype.constructor
back to A
. So it now points to C
. This causes problems in the constructor B
if we use the second method:
var C = function C() {
// some code
};
var A = function A() {
this.x = 123;
};
A.prototype = Object.create(C.prototype);
// I forgot to uncomment the next line:
// A.prototype.constructor = A;
var B = function B() {
// 1. call directly
A.call(this);
// 2. call from prototype
A.prototype.constructor.call(this); // A.prototype.constructor is C, not A
};
B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;
A
inherited a constructor from another object? – Ilia Choly Commented Nov 7, 2012 at 14:58