javascript エラー「ReferenceError: ‘super()’ must be called in derived constructor before accessing |this| or returning non-object.」の解決方法

javascript エラー「ReferenceError: ‘super()’ must be called in derived constructor before accessing |this| or returning non-object.」の解決方法

javascriptで、エラー「ReferenceError: ‘super()’ must be called in derived constructor before accessing |this| or returning non-object.」が発生した場合の原因と解決方法を記述してます。

環境

  • OS macOS Big Sur
  • ブラウザ safari 15.5

エラー内容

以下の、クラスのコンストラクタをオーバーライドした以下のコードを実行時に発生。

class A {

    constructor( num ) {
        this._num = num;
    }

}

class B extends A {

    constructor( num, str ) {        
        this._num = num;
        this._str = str;
    }

    disp() {
        return this._str
    }

}

const b = new B( 100, "hello js!!" );

console.log( b.disp() );

エラーメッセージ

ReferenceError: 'super()' must be called in derived constructor before accessing |this| or returning non-object.

画像

原因

親クラスのコンストラクタをオーバーライドするには、「super()」を使用して親クラスのコンストラクタを呼び出す必要があるため

解決方法

「super()」をオーバーライド先で使用する

class A {

    constructor( num ) {
        this._num = num;
    }

}

class B extends A {

    constructor( num, str ) {     
        super();   
        this._num = num;
        this._str = str;
    }

    disp() {
        return this._str
    }

}

const b = new B( 100, "hello js!!" );

console.log( b.disp() ); // hello js!!