The concept of super
keyword comes with the idea of inheritance in JavaScript. Suppose that you have a member variable or method of the same name in the derived class as you do in the base class.
When referring to that variable/method, how would the program know if you are referring to the base class or the derived class?
This is where super
comes into play. The super
keyword in JavaScript acts as a reference variable to the parent class.
It is mainly used when we want to access a variable, method, or constructor in the base class from the derived class.
Let’s have a look at some examples to understand exactly how the super
keyword works.
super
in classesHere, super()
is called to avoid duplicating the constructor parts that are common between Rectangle
and Square
:
class Rectangle {constructor(height, width) {this.name = 'Rectangle';this.height = height;this.width = width;}getName() {console.log('Hi, I am a ', this.name + '.');}}class Square extends Rectangle {constructor(length) {// Can't use this.height. It will throw a reference error// It calls the parent class's constructorsuper(length, length);// In derived classes, super() must be called before you// can use 'this'.this.name = 'Square';}}
super
in static methodssuper
can also be used to call on static methods of the parent class:
class Rectangle {constructor() {}static getDescription() {return 'I have 4 sides';}}class Square extends Rectangle {constructor() {super()}static getDescription() {return super.getDescription() + ' which are all equal';}}console.log(Square.getDescription())
Free Resources