JS Classes: Extend and Super Keyword
Asif Zubayer Palak
Posted on March 29, 2023
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}`;
}
}
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();
}
}
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;
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();
}
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
Posted on March 29, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 30, 2024