/

Understanding the JavaScript Super Keyword

Understanding the JavaScript Super Keyword

When developing with classes in JavaScript, you often come across the super keyword. In this blog post, let’s explore the purpose and usage of super.

Let’s start with a simple example. We have a class called Car:

1
2
3
4
5
class Car {
constructor() {
console.log('This is a car');
}
}

The constructor method in a class is special because it is executed when the class is instantiated. For example:

1
const myCar = new Car(); //'This is a car'

Now, let’s say we have a class called Tesla that extends the Car class:

1
2
3
class Tesla extends Car {

}

The Tesla class inherits all the methods and properties of the Car class, including the constructor method. So, when we create an instance of the Tesla class, it will execute the Car class constructor as well:

1
const myCar = new Tesla();

If we want to override the constructor method in the Tesla class, we can do so:

1
2
3
4
5
class Tesla extends Car {
constructor() {
console.log('This is a Tesla');
}
}

Now, when we create a Tesla object, it will display 'This is a Tesla' instead.

1
const myCar = new Tesla(); //'This is a Tesla'

In the constructor method, we can also invoke the same method in the parent class using super(). This allows us to perform the logic of the parent class constructor before adding additional logic:

1
2
3
4
5
6
class Tesla extends Car {
constructor() {
super();
console.log('This is a Tesla');
}
}

Now, when we create a Tesla object, both the Car class constructor and the Tesla class constructor will be executed:

1
2
3
const myCar = new Tesla();
//'This is a car'
//'This is a Tesla'

Keep in mind that super() can only be called within the constructor and not in other methods. Additionally, if the parent constructor accepts parameters, you can pass them in when using super().

To summarize, the super keyword in JavaScript classes allows us to call and extend the functionality of the parent class constructor.

tags: [“JavaScript”, “programming”, “classes”, “super keyword”]