A “SyntaxError: Cannot use ‘super’ without ‘extends’” exception in JavaScript crops up when super is called through a class method but the class does not come from an extended class, the super keyword is supported as a means of invoking the parent class constructor or methods, and it must be used only on an ordinary class that extends a base one, let us study this error, its causes and how to solve it.
Understanding an errorIf you see an error that says you cannot say ‘super’ without mentioning ‘extends,’ it means you wrongly used the super keyword within a class that does not extend other classes. In this regard, while relying on the parent class constructor or methods, the super keyword should only be applicable in classes that inherit from them.
Case 1: Using super in a Class without extends Error Cause:When you attempt using the super keyword in a class that doesn’t inherit from another compile time error pops up.
Example:class MyClass { constructor() { super(); } }
const myInstance = new MyClass(); Output:SyntaxError: Cannot use 'super' without 'extends' Resolution of error:To correct this error make sure that when using the super keyword the class is extending another one.
JavaScript
//script.js
class ParentClass {
constructor() {
console.log("Parent class constructor");
}
}
class MyClass extends ParentClass {
constructor() {
super();
console.log("Child class constructor");
}
}
const myInstance = new MyClass();
OutputParent class constructor Child class constructor Case 2: Using super in a Method without extends Error Cause: That would cause this error if you try to use the super keyword in a method of a class which doesn’t extend any other class.
Example:
class MyClass { myMethod() { super.myMethod(); } }
const myInstance = new MyClass(); myInstance.myMethod(); Output:
SyntaxError: Cannot use 'super' without 'extends' Resolution of error:For using the super keyword in method, make sure that it extends some other class.
JavaScript
//script.js
class ParentClass {
myMethod() {
console.log("Parent method");
}
}
class MyClass extends ParentClass {
myMethod() {
super.myMethod();
console.log("Child method");
}
}
const myInstance = new MyClass();
myInstance.myMethod();
Output:Parent method Child method ConclusionIn conclusion to avoid getting “Cannot use ‘super’ without ‘extends’” errors in JavaScript, make sure you only use super inside classes which extend other ones. This will help you follow JavaScript’s rules of inheritance among classes and make calls to constructors/methods of parent classes appropriately.
|