调用基础构造函数 - Javascript

Ili*_*oly 11 javascript inheritance prototype

有两种方法可以调用子进程中的父构造函数.

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;
Run Code Online (Sandbox Code Playgroud)

是否有任何情况下,一个人比另一个人更安全/更好,或者他们总是相同?

Aad*_*hah 17

由于以下原因,最好直接使用基础构造函数:

  1. 它更快.解释器不需要访问prototype.constructor.
  2. 它更安全.考虑下面的程序.

A继承自C,但我忘了A.prototype.constructor回到A.所以它现在指向C.B如果我们使用第二种方法,这会在构造函数中导致问题:

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;
Run Code Online (Sandbox Code Playgroud)