Home > database >  Javascript Class ReferenceError
Javascript Class ReferenceError

Time:06-04

It's about JS class from MDN page. I don't understand why Bad class has a reference error. Is it because empty constructor of Bad class calls super() as a default?

class Base {}

class Good extends Base {}

class AlsoGood extends Base {

constructor() {

return {a: 5};

}

}

class Bad extends Base {

constructor() {}

}

new Good();

new AlsoGood();

new Bad(); // ReferenceError

CodePudding user response:

To avoid getting this error you must either remove constructor from the class or call super() inside the constructor of the Bad class

CodePudding user response:

Is it because empty constructor of Bad class calls super() as a default?

No - if the empty constructor did call super by default, you wouldn't be seeing the error.

A derived class's constructor, if it exists, must call the parent's constructor with super.

If a derived class lacks any constructor at all, super will be called automatically. That is

class Good extends Base {
}

is equivalent to

class Good extends Base {
  constructor(...args) {
    super(...args);
  }
}

The same does not extend to empty constructors - if the constructor is present, super does not get called automatically - but super must be called.

  • Related