Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. JavaScript
  3. Reference
  4. JavaScript error reference
  5. ReferenceError: super() called twice in derived class constructor

ReferenceError: super() called twice in derived class constructor

The JavaScript exception "super() called twice in derived class constructor" occurs when thesuper() 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?

Thesuper() call can only be called at most once for eachnew call to a derived class constructor. This is becausesuper() 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 thatsuper() is placed outside of any control flow structure. Otherwise, make sure that all code paths in the constructor lead to only onesuper() call.

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

Examples

Invalid cases

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

Sometimes the bug may be more subtle.

js
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 callsuper() twice. You need to rethink about how your class should be structured to avoid this issue.

Valid cases

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

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp