大网数据广告活动
Web 标准与前端开发

ReferenceError: super() called twice in derived class constructor

· 52CE 我爱测

The JavaScript exception "super() called twice in derived class constructor" occurs when the Operators/super is called a second time for a given derived class constructor.

The JavaScript exception "super() called twice in derived class constructor" occurs when the Operators/super is called a second time for a given derived class constructor.

Message

ReferenceError: Super constructor may only be called once (V8-based)
ReferenceError: super() called twice in derived class constructor (Firefox)
ReferenceError: 'super()' can't be called more than once in a constructor. (Safari)

Error type

ReferenceError

What went wrong?

The super() call can only be called at most once for each new call to a derived class constructor. This is because super() is responsible for initializing the parent class, and calling it more than once would result in the parent constructor being called multiple times.

The best way to prevent this is to ensure that super() is placed outside of any control flow structure. Otherwise, make sure that all code paths in the constructor lead to only one super() call.

The super() call can be "saved" in an arrow function nested within the constructor. Then, when you call the arrow function, you will also call super(), and the same rule applies: the arrow function can only be called at most once.

Examples

Invalid cases

class Base {}

class Derived extends Base {
  constructor() {
    super();
    super();
  }
}

Sometimes the bug may be more subtle.

class Base {
  constructor(flavor) {
    // Do something with the flavor
  }
}

class Derived extends Base {
  constructor(flavors) {
    if (flavors.includes("chocolate")) {
      super("chocolate");
    }
    if (flavors.includes("vanilla")) {
      super("vanilla");
    }
  }
}

Originally, flavors may never simultaneously include both "chocolate" and "vanilla", but if that ever happens, the constructor will call super() twice. You need to rethink about how your class should be structured to avoid this issue.

Valid cases

class Base {}

class Derived extends Base {
  constructor() {
    super();
    // More initialization logic
  }
}

See also

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。