Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. JavaScript
  3. Reference
  4. JavaScript error reference
  5. ReferenceError: must call super constructor before using 'this' in derived class constructor

ReferenceError: must call super constructor before using 'this' in derived class constructor

The JavaScript exception "must call super constructor before using 'this' in derived class constructor" occurs when thesuper() is not called for a given derived class constructor, and the derived constructor tries to access the value ofthis, or the derived constructor has already returned and the return value is not an object.

Message

ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor (V8-based)ReferenceError: must call super constructor before using 'this' in derived class constructor (Firefox)ReferenceError: 'super()' must be called in derived constructor before accessing |this| or returning non-object. (Safari)

Error type

ReferenceError

What went wrong?

Thesuper() call can only be called at most once for eachnew call to a derived class constructor. Often, you need to call it exactly once, because if you don't call it, the parent constructor cannot initialize the value ofthis, so you cannot accessthis in the derived constructor and thethis is not considered a valid constructed object (and throws if the derived constructor completes in this state). The way around it is to return an object from the derived class constructor, in which case the object returned will be used as the constructed object instead ofthis, allowing you to not callsuper(). This is rarely done though.

Examples

Invalid cases

js
class Base {  constructor() {    this.x = 1;  }}class Derived extends Base {  constructor() {    console.log(this.x);    // The Base constructor is not called yet, so this.x is undefined    // ReferenceError: must call super constructor before using 'this' in derived class constructor  }}

Valid cases

js
class Base {  constructor() {    this.x = 1;  }}class Derived extends Base {  constructor() {    super();    console.log(this.x); // 1  }}

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp