Skip to main content

Inheritance

Inheritance is a core principle of OOP. It allows you to create a "Child" class that automatically inherits all the logic and traits from a "Parent" class, while still allowing the Child to have its own unique logic.

In JavaScript, this is achieved via the extends keyword in combination with super.

Extends and Super

class Animal {
constructor(name) {
this.name = name;
}

speak() {
console.log(`${this.name} makes a noise.`);
}
}

// Dog INHERITS from Animal
class Dog extends Animal {
constructor(name, breed) {
// 'super' actively fires the parent Animal constructor!
super(name);
this.breed = breed;
}

// Overriding the parent's method (Polymorphism)
speak() {
console.log(`${this.name} barks loudly!`);
}

fetch() {
console.log(`${this.name} fetches the stick.`);
}
}

const myDog = new Dog("Buddy", "Golden Retriever");

myDog.speak(); // "Buddy barks loudly!" (Uses the child method)
myDog.fetch(); // "Buddy fetches the stick."

The Prototype Chain Concept

When you invoke myDog.speak(), the JS Engine handles inheritance under the hood via the Prototype Chain:

  1. It checks the myDog instance itself.
  2. It checks the Dog prototype. (Found it! Executes.)
  3. If it wasn't there, it would travel up to the Animal prototype.
  4. If not there, it travels up to the master Object prototype.