11

有两种方法可以在子级中调用父级构造函数。

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;

有没有一种情况会比另一种更安全/更好,或者它们总是相同的?

4

1 回答 1

18

出于以下原因,直接使用基本构造函数总是更好:

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

A继承自C,但我忘记设置A.prototype.constructorA. 所以它现在指向CB如果我们使用第二种方法,这会导致构造函数出现问题:

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;
于 2012-11-07T14:50:07.900 回答