In javascript ES6, in inheritance,
if derived class has constructor, why it is mandatory to call super from derived constructor ?
few failed examples are -:
. Base with constructor but derived not calling super-
class Base{constructor(){}}
class Derived{constructor(){}}
var d = new Derived(); // fails - ReferenceError: this is not defined
Not really. If you don't provide one, one will be provided for you by the JavaScript engine. So there will always be one (it's mandatory in that sense), but it doesn't have to be coded explicitly.
When you don't define a constructor at all, the default one provided by the JavaScript engine for a base class will look like this:
...and the default one in a derived class will look like this:
The reason your example fails is that
Derived
has an explicitconstructor
, but thatconstructor
doesn't callsuper
. You must callsuper
from withinDerived
's constructor if you explicitly define one.Because you are required to give the superclass an opportunity to do any initialization of the new object that it has to do. Otherwise, the superclass can't guarantee that it will work correctly, as it may rely on the initialization done by its constructor.
So either:
Remove your
constructor
fromDerived
, making it like your first example so that the JavaScript engine will provide the default constructor, orCall
super
fromDerived
's constructor.In a comment you asked:
The base class always has a constructor, because if you don't provide one (you did in the code in your question), a default is provided. So you still have to call it. While it could have been specified as optional if none of the superclasses had a non-default constructor, that would be adding complexity and making
Derived
's explicit constructor misleading (no call tosuper
).There are also some mechanical reasons:
this
isn't defined until you callsuper
, but you're allowed to do things prior to callingsuper
, so making the call is necessary to handle the mechanics ofthis
in the spec.