In JavaScript, class-based inheritance allows us to create classes that inherit properties and methods from other classes. The concept of class-based inheritance is important in object-oriented programming as it promotes code reusability and modularity. In this blog post, we will explore how to achieve class-based inheritance in JavaScript.
Creating Base Class
To start with class-based inheritance, we need to create a base class. This class will contain the common properties and methods that will be inherited by the derived classes. Let’s create a Shape
class as an example:
class Shape {
constructor(color) {
this.color = color;
}
getColor() {
return this.color;
}
draw() {
console.log("Drawing a shape");
}
}
The Shape
class has a constructor that accepts a color
parameter and assigns it to the instance variable color
. It also has getColor()
and draw()
methods which can be used by the derived classes.
Creating Derived Classes
To create a derived class that inherits from the base class, we use the extends
keyword. Let’s create a Circle
class that inherits from the Shape
class:
class Circle extends Shape {
constructor(radius, color) {
super(color);
this.radius = radius;
}
getRadius() {
return this.radius;
}
draw() {
console.log(`Drawing a circle with radius ${this.radius}`);
}
}
The Circle
class extends the Shape
class using the extends
keyword. It also has a constructor that accepts a radius
parameter. Inside the constructor, we call the super
keyword to invoke the constructor of the base class. This is necessary to initialize the inherited properties. The Circle
class also has a getRadius()
method and overrides the draw()
method with a specific implementation.
Using the Classes
Now, let’s see how we can create objects of the derived classes and use their inherited properties and methods:
const circle = new Circle(5, "red");
console.log(circle.getColor()); // Output: red
console.log(circle.getRadius()); // Output: 5
circle.draw(); // Output: Drawing a circle with radius 5
We create a circle
object using the Circle
class constructor. We can access the inherited getColor()
method from the Shape
class, as well as the getRadius()
and draw()
methods specific to the Circle
class.
Conclusion
Class-based inheritance is a powerful feature in JavaScript that allows us to create complex and hierarchical class structures. By leveraging class-based inheritance, we can write efficient and modular code. In this blog post, we learned how to create a base class and derived classes, and how to use inherited properties and methods. Understanding and utilizing class-based inheritance is crucial for building scalable and maintainable JavaScript applications.