Class Inheritance in JavaScript (Live Playground)
Inheritance is an important concept in object-oriented programming, allowing you to create new classes that inherit properties and methods from existing classes. In this tutorial, we'll learn about inheritance in JavaScript classes and how to extend classes using the extends keyword.
Extending Classes
To create a new class that inherits from an existing class, use the extends keyword followed by the parent class name:
class Shape {
constructor(color) {
this.color = color;
}
getColor() {
return this.color;
}
}
class Circle extends Shape {
constructor(color, radius) {
super(color);
this.radius = radius;
}
getArea() {
return Math.PI * Math.pow(this.radius, 2);
}
}
const circle = new Circle('blue', 100);
console.log(circle.getArea());
In this example, the Circle class extends the Shape class, inheriting its properties and methods. The constructor function of the Circle class calls the super function to invoke the parent class's constructor.
Using the super Keyword
The super keyword is used to call the parent class's constructor, methods, or both:
class Rectangle extends Shape {
constructor(color, width, height) {
super(color);
this.width = width;
this.height = height;
}
getArea() {
return this.width * this.height;
}
getColor() {
return `The color of this rectangle is ${super.getColor()}`;
}
}
const rect = new Rectangle('blue', 100, 200);
console.log(rect.getArea());
console.log(rect.getColor());
In this example, the Rectangle class also extends the Shape class. We've overridden the getColor method in the Rectangle class, and we use the super keyword to access the getColor method of the parent class.
Conclusion
In this tutorial, we learned about inheritance and extending classes in JavaScript, including how to create subclasses that inherit properties and methods from parent classes, and how to use the super keyword to access parent class methods. By using inheritance, you can create new classes with shared functionality, which helps you write more efficient and maintainable code.