SyntaxError: super() is only valid in derived class constructors

super() 呼叫在非派生類(使用 extends 關鍵字的類)的 建構函式 體內使用時,會丟擲 JavaScript 異常 "super() 只能在派生類建構函式中呼叫"。

訊息

SyntaxError: 'super' keyword unexpected here (V8-based)
SyntaxError: super() is only valid in derived class constructors (Firefox)
SyntaxError: super is not valid in this context. (Safari)

錯誤型別

SyntaxError

哪裡出錯了?

super() 呼叫用於呼叫派生類的基類建構函式,以便基類可以初始化 this 物件。在其他任何地方使用它都沒有意義。

super() 也可以在建構函式中巢狀的箭頭函式中定義。但是,它不能在其他任何型別的函式中定義。

示例

無效案例

如果類沒有 extends 關鍵字,則不能呼叫 super(),因為沒有基類可供呼叫。

js
class Base {
  constructor() {
    super();
  }
}

即使類方法是從建構函式中呼叫的,也不能在類方法中呼叫 super()

js
class Base {}

class Derived extends Base {
  constructor() {
    this.init();
  }

  init() {
    super();
  }
}

即使函式用作建構函式,也不能在函式中呼叫 super()

js
function Base(x) {
  this.x = x;
}

function Derived() {
  super(1);
}

Object.setPrototypeOf(Derived.prototype, Base.prototype);
Object.setPrototypeOf(Derived, Base);

有效情況

可以在建構函式中呼叫任何其他方法之前呼叫 super()

js
class Base {}

class Derived extends Base {
  constructor() {
    super();
    this.init();
  }

  init() {
    // …
  }
}

可以在建構函式中巢狀的箭頭函式中呼叫 super()

js
class Base {}

class Derived extends Base {
  constructor() {
    const init = () => {
      super();
    };

    init();
  }
}

另見