SyntaxError: super() is only valid in derived class constructors
The JavaScript exception "super() is only valid in derived class constructors" occurs when thesuper() call is used somewhere that's not the body of aconstructor in a class withextends keyword.
In this article
Message
SyntaxError: 'super' keyword unexpected here (V8-based)SyntaxError: super() is only valid in derived class constructors (Firefox)SyntaxError: super is not valid in this context. (Safari)
Error type
SyntaxErrorWhat went wrong?
Thesuper() call is used to invoke the base constructor of a derived class, so the base class can initialize thethis object. Using it anywhere else doesn't make sense.
super() can also be defined in an arrow function that's nested within the constructor. However, it cannot be defined in any other kind of function.
Examples
>Invalid cases
You cannot callsuper() if the class has noextends, because there's no base class to call:
class Base { constructor() { super(); }}You cannot callsuper() in a class method, even if that method is called from the constructor:
class Base {}class Derived extends Base { constructor() { this.init(); } init() { super(); }}You cannot callsuper() in a function, even if the function is used as a constructor:
function Base(x) { this.x = x;}function Derived() { super(1);}Object.setPrototypeOf(Derived.prototype, Base.prototype);Object.setPrototypeOf(Derived, Base);Valid cases
You can callsuper() before calling any other method in the constructor:
class Base {}class Derived extends Base { constructor() { super(); this.init(); } init() { // … }}You can callsuper() in an arrow function that's nested within the constructor:
class Base {}class Derived extends Base { constructor() { const init = () => { super(); }; init(); }}