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
  }
}

另見