Inheritance is a fundamental concept in object-oriented programming that allows one class (child) to inherit properties and methods from another class (parent). JavaScript supports both prototypal inheritance and class-based inheritance.
In JavaScript, inheritance helps in reusing code by creating a new class from an existing class. Prior to ES6, JavaScript relied on prototype-based inheritance, but ES6 introduced the class
keyword, making it easier to work with OOP concepts.
With prototypal inheritance, objects inherit properties and methods from another object using Object.create()
. With class-based inheritance, we use the extends
keyword to define a subclass.
Here’s an example demonstrating class-based inheritance in JavaScript:
// Parent class
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise`);
}
}
// Child class inheriting from Animal
class Dog extends Animal {
speak() {
console.log(`${this.name} barks`);
}
}
const dog = new Dog("Buddy");
dog.speak(); // Output: Buddy barks
This allows Dog
to inherit from Animal
, ensuring code reusability and cleaner structure.