Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling base constructor - Javascript

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?

like image 954
Ilia Choly Avatar asked Nov 07 '12 14:11

Ilia Choly


People also ask

How do you call a constructor in JavaScript?

In JavaScript, a constructor gets called when an object is created using the new keyword.

Can you call a method in a constructor JavaScript?

Yes, it is possible, when your constructor function executes, the this value has already the [[Prototype]] internal property pointing to the ValidateFields.

How do you call the constructor of a parent class in JavaScript?

The super keyword is used to call the constructor of its parent class to access the parent's properties and methods.

What does super () do in JS?

The super keyword is used to access properties on an object literal or class's [[Prototype]], or invoke a superclass's constructor. The super. prop and super[expr] expressions are valid in any method definition in both classes and object literals.


1 Answers

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;
like image 167
Aadit M Shah Avatar answered Nov 15 '22 16:11

Aadit M Shah