ReferenceError: must call super constructor before using 'this' in derived class constructor

当给定派生类构造函数未调用 super(),且派生构造函数试图访问 this 的值,或者派生构造函数已经返回但返回值不是一个对象时,就会发生 JavaScript 异常 "派生类构造函数在使用 'this' 之前必须调用超类构造函数"。

消息

ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor (V8-based)
ReferenceError: must call super constructor before using 'this' in derived class constructor (Firefox)
ReferenceError: 'super()' must be called in derived constructor before accessing |this| or returning non-object. (Safari)

错误类型

ReferenceError

哪里出错了?

对于派生类构造函数的每个 new 调用,super() 最多只能被调用一次。通常,你需要精确地调用它一次,因为如果你不调用它,父构造函数无法初始化 this 的值,因此你无法在派生构造函数中访问 this,并且 this 不被视为有效的构造对象(如果派生构造函数在此状态下完成,则会抛出错误)。解决办法是从派生类构造函数返回一个对象,在这种情况下,返回的对象将用作构造对象而不是 this,从而允许你不调用 super()。不过,这种情况很少见。

示例

无效案例

js
class Base {
  constructor() {
    this.x = 1;
  }
}

class Derived extends Base {
  constructor() {
    console.log(this.x);
    // The Base constructor is not called yet, so this.x is undefined
    // ReferenceError: must call super constructor before using 'this' in derived class constructor
  }
}

有效情况

js
class Base {
  constructor() {
    this.x = 1;
  }
}

class Derived extends Base {
  constructor() {
    super();
    console.log(this.x); // 1
  }
}

另见