In JavaScript, the super
keyword is used to call the constructor and methods of an object’s parent class, and to access its
properties.
The expression super(...args)
is used to call the parent’s constructor. It must be used carefully and correctly to avoid errors.
class Dog extends Animal {
constructor(name) {
super();
this.name = name;
super(); // Noncompliant: constructor is called twice.
super.doSomething();
}
}
Follow these instructions when invoking the parent’s constructor:
-
super()
cannot be invoked in the constructor of a non-derived class.
-
super()
must be invoked in the constructor of a derived class.
-
super()
must be invoked before the this
and super
keywords can be used.
-
super()
must be invoked with the same number of arguments as the base class' constructor.
-
super()
can only be invoked in a constructor - not in any other method.
-
super()
cannot be invoked multiple times in the same constructor.
class Dog extends Animal {
constructor(name) {
super();
this.name = name;
super.doSomething();
}
}
Some issues are not raised if the base class is not defined in the same file as the current class. This is a known limitation of this rule.