TypeError: class constructors must be invoked with 'new'

類建構函式在沒有 new 關鍵字的情況下被呼叫時,會丟擲 JavaScript 異常“類建構函式必須使用 'new' 呼叫”。所有類建構函式都必須使用 new 呼叫。

訊息

TypeError: Class constructor X cannot be invoked without 'new' (V8-based)
TypeError: Class constructors cannot be invoked without 'new' (V8-based)
TypeError: class constructors must be invoked with 'new' (Firefox)
TypeError: Cannot call a class constructor without |new| (Safari)

錯誤型別

TypeError

哪裡出錯了?

在 JavaScript 中,不帶 new 呼叫函式和帶 new 構造函式是兩種截然不同的操作,函式可能會根據它們的呼叫方式表現出不同的行為。

傳統上,JavaScript 函式既可以作為建構函式使用,也可以作為普通函式使用,並且可以使用 new.target 檢測它們的呼叫方式。但是,類建構函式始終是建構函式,不能作為普通函式呼叫。

示例

無效案例

js
class X {}

X(); // TypeError: class constructors must be invoked with 'new'

有效情況

js
class X {}

new X();

另見