Overriding Parent Methods
What you'll learn: How child classes can replace inherited methods by defining their own version with the same name.
When you inherit from a parent class using extends, you automatically get all of its methods. But what if you want a child class to do something differently from its parent? You can override a parent method by simply defining a method with the exact same name in the child class.
How Method Overriding Works
When JavaScript looks for a method on an instance, it searches the prototype chain. It checks the child class first, then the parent. If the child defines a method with the same name as one in the parent, the child's version is found first and used instead. The parent's method still exists—it's just hidden by the child's version.
Think of it like a family recipe. Your parent has a recipe for cookies. You inherit that recipe, but you decide to make your own version with extra chocolate chips. When someone asks you for cookies, they get your version, not your parent's—even though your parent's recipe still exists.
Basic Example
class Animal {
speak() {
return "Some generic sound";
}
}
class Dog extends Animal {
speak() {
return "Woof!";
}
}
const myDog = new Dog();
console.log(myDog.speak()); // "Woof!" (child version used)
const genericAnimal = new Animal();
console.log(genericAnimal.speak()); // "Some generic sound"
The Dog class completely replaces the speak() method. When you call speak() on a Dog instance, you get "Woof!", not the generic sound.
Key Takeaway: Defining a method in a child class with the same name as a parent method completely overrides the parent's version—the child's implementation takes precedence.