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();

另见