DEV Community

Asif Zubayer Palak
Asif Zubayer Palak

Posted on

JS Classes: Extend and Super Keyword

Extend and Super Keywords are used to implement Inheritance in JS.

The extends keyword, as the name suggests, extends a class - meaning, one class inherits the properties from another class.

The super keyword refers to superclass or parent objects. It is used to call and to access superclass methods and constructor.

How to use the Extend and Super Keywords?

class Vehicle{
 constructor(vehicleType,numofSeats){
   this.vehicleType = vehicleType;
   this.numofSeats = numofSeats;
   this.forSale = false;
 }
 describe(){
  return `This ${vehicleType} has ${numofSeats}`;
 }
}
Enter fullscreen mode Exit fullscreen mode

Here we will use the extend keyword to inherit the properties of the Vehicle class.

class Car extends Vehicle{
  constructor(vehicleType,numofSeats,color){
    super(vehicleType,numofSeats);
     this.color = color;
     this.forSale = true;
  }
  describe(){
    super();
  }
}

Enter fullscreen mode Exit fullscreen mode

super calls the constructor function of the Vehicle class since we are extending from Vehicle.

Doing so reduces your hassle of writing

this.vehicleType = vehicleType;
this.numofSeats = numofSeats;
Enter fullscreen mode Exit fullscreen mode

all over again for the Car class.

color is a property that was not in the Vehicle class, therefore - we add it in the Car constructor and assign this.color to color.
Since we are selling the Car, this.forSale should be set to true.

In case of functions, you can also inherit and call it from the parent class. Such as the code snippet

describe(){
  super();
}
Enter fullscreen mode Exit fullscreen mode

as shown in the code above invokes the super function inside the describe() function. What this does is the Car class invokes the describe function from the Vehicle class. Meaning that the Car subclass is calling the describe()function from the Vehicle class while using the parameters of the Car subclass.

To learn about static methods, check out JS Classes: Static Methods

Top comments (0)