DEV Community

Asif Zubayer Palak
Asif Zubayer Palak

Posted on

1

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

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post →

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

Best practices for optimal infrastructure performance with Magento

Running a Magento store? Struggling with performance bottlenecks? Join us and get actionable insights and real-world strategies to keep your store fast and reliable.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️