Inheritance is a crucial concept in JavaScript that allows objects to inherit properties and methods from other objects. It's a fundamental principle of object-oriented programming, enabling code reuse and creating hierarchical relationships between classes.
JavaScript uses prototypal inheritance, where objects can inherit directly from other objects. This is different from class-based inheritance found in languages like Java or C++.
// Parent object
const Animal = {
makeSound() {
console.log("Some generic animal sound");
}
};
// Child object
const Dog = Object.create(Animal);
Dog.bark = function() {
console.log("Woof!");
};
Dog.makeSound(); // Outputs: Some generic animal sound
Dog.bark(); // Outputs: Woof!
With the introduction of ES6, JavaScript added syntactic sugar for creating class-like structures, making inheritance more intuitive for developers coming from class-based languages.
class Animal {
constructor(name) {
this.name = name;
}
makeSound() {
console.log(`${this.name} makes a sound`);
}
}
class Dog extends Animal {
bark() {
console.log(`${this.name} barks`);
}
}
const myDog = new Dog("Buddy");
myDog.makeSound(); // Outputs: Buddy makes a sound
myDog.bark(); // Outputs: Buddy barks
The extends
keyword is used to create a class that is a child of another class. It sets up the prototype chain for you automatically.
When extending a class, you can use the super
keyword to call functions on the parent class. This is particularly useful in constructors:
class Cat extends Animal {
constructor(name, lives) {
super(name); // Call the parent constructor
this.lives = lives;
}
meow() {
console.log(`${this.name} meows`);
}
}
const myCat = new Cat("Whiskers", 9);
myCat.makeSound(); // Outputs: Whiskers makes a sound
myCat.meow(); // Outputs: Whiskers meows
Object.prototype
by default.instanceof
to check if an object is an instance of a particular class.Mastering inheritance in JavaScript opens up powerful ways to structure your code. It's closely related to JavaScript Objects and JavaScript Classes, which are essential concepts to grasp for effective object-oriented programming in JavaScript.
To deepen your understanding of JavaScript inheritance and related concepts, explore these topics:
By mastering these concepts, you'll be well-equipped to create efficient, reusable, and well-structured JavaScript code.