Member-only story
Object-oriented programming (OOP) is a widely used programming paradigm that allows developers to create reusable and modular code. One of the key concepts in OOP is inheritance, which enables the creation of new classes based on existing ones, inheriting their properties and methods.
In JavaScript, class inheritance is achieved through a powerful feature called prototypal inheritance.
Before we dive into class inheritance, let’s quickly review the basics of classes in JavaScript.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound.`);
}
}
const dog = new Animal('Buddy');
dog.speak(); // Output: Buddy makes a sound.
In the above example, we have a Animal
class with a constructor that accepts a name
parameter and initializes it as a property of the object instance. The class also has a speak
method that logs a message to the console.
Now, let’s explore how we can create a new class that inherits from the Animal
class using the extends
keyword and the super
method.
class Dog extends Animal {
constructor(name) {…