11

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?

Ilia Choly
  • 18,070
  • 14
  • 92
  • 160
  • What would compel you to use the second version? You're just taking a long path to get to the same function. – I Hate Lazy Nov 07 '12 at 14:51
  • Maybe a situation where `A` inherited a constructor from another object? – Ilia Choly Nov 07 '12 at 14:58
  • Alright, but then the two calls are not equivalent. You're talking about two different situations. – I Hate Lazy Nov 07 '12 at 15:01
  • Hence the last part of the question. – Ilia Choly Nov 07 '12 at 15:02
  • But if you're describing a situation where they are not equivalent, then you already know they may not be not equivalent, so why ask the question? If the situation is such that you know they *are* equivalent, then what would compel you to use the second version? – I Hate Lazy Nov 07 '12 at 15:03
  • I had a rough idea, @Aadit reinforced/clarified it. – Ilia Choly Nov 07 '12 at 15:07
  • @iliacholy - From what I see you're doing in your code, perhaps you might find the following answer interesting: http://stackoverflow.com/a/12041555/783743 – Aadit M Shah Nov 07 '12 at 15:14

1 Answers1

18

It's always better to use the base constructor directly for the following reasons:

  1. It's faster. The interpreter doesn't need to access prototype.constructor.
  2. 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;
Aadit M Shah
  • 72,912
  • 30
  • 168
  • 299