Inheriting Methods from the Parent
You'll learn: How child classes automatically gain access to all the methods defined in their parent class, making code reuse effortless.
The Core Idea
When you use extends to create a child class, JavaScript automatically sets up the prototype chain so that every method you defined in the parent class becomes available to instances of the child class. You don't need to copy anything manually—inheritance just works.
Think of it like inheriting family traits: if your parent knows how to whistle, you can whistle too without having to learn it separately. The child class "borrows" methods from the parent through the prototype chain.
How It Works
When you call a method on a child class instance, JavaScript first looks for that method on the child class itself. If it doesn't find it there, JavaScript automatically climbs up to the parent class and uses the method defined there. This happens transparently—you call the method as if it were defined directly on the child.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound`;
}
sleep() {
return `${this.name} is sleeping`;
}
}
class Dog extends Animal {
constructor(name) {
super(name);
}
}
const buddy = new Dog('Buddy');
console.log(buddy.speak()); // "Buddy makes a sound"
console.log(buddy.sleep()); // "Buddy is sleeping"
Even though Dog doesn't define speak() or sleep(), every Dog instance can call these methods because they inherited them from Animal.
Key Takeaway: Child classes automatically inherit all parent methods through the prototype chain, enabling powerful code reuse without any extra effort.