There are situations where super()
must be invoked and situations where super()
cannot be invoked.
The basic rule is: a constructor in a non-derived class cannot invoke super()
; a constructor in a derived class must invoke
super()
.
Furthermore:
-
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.
Known Limitations
- False negatives: some issues are not raised if the base class is not defined in the same file as the current class.
Noncompliant Code Example
class Dog extends Animal {
constructor(name) {
super();
this.name = name;
super(); // Noncompliant
super.doSomething();
}
}
Compliant Solution
class Dog extends Animal {
constructor(name) {
super();
this.name = name;
super.doSomething();
}
}