start learning
Image 1
4477441512747

Inheritance JavaScript Object-Oriented Programming (OOP)

Inheritance allows classes to inherit properties and methods from their parent classes, enabling code reuse and promoting a hierarchical structure.


Single-Level Inheritance


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

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

class Dog extends Animal {
  constructor(name) {
    super(name);
  }

  speak() {
    console.log(`${this.name} how.`);
  }
}

const dog = new Dog('Blob');
dog.speak(); // Output: Blob how.

In this example, Dog is a subclass that inherits from the Animal superclass. The Dog class extends the Animal class using the extends keyword. It calls the superclass constructor using super(name). The speak method is overridden in the Dog class to provide a specific implementation. The instance of Dog can access both its own methods and the inherited methods from the Animal class.


Multilevel Inheritance


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

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

class Dog extends Animal {
  constructor(name) {
    super(name);
  }

  speak() {
    console.log(`${this.name} barks.`);
  }
}

class Puppy extends Dog {
  constructor(name) {
    super(name);
  }

  speak() {
    console.log(`${this.name} makes cute puppy noises.`);
  }
}

const puppy = new Puppy('Max');
puppy.speak(); // Output: Max makes cute puppy noises.
puppy instanceof Dog; // Output: true
puppy instanceof Animal; // Output: true

In this example, Puppy is a subclass that inherits from the Dog class, which in turn inherits from the Animal superclass. This demonstrates multilevel inheritance. The Puppy class inherits the speak method from both the Dog and Animal classes. An instance of Puppy can access methods from all three classes in the inheritance chain.


Mixin-based Inheritance


const sayNameMixin = {
  sayName() {
    console.log(`My name is ${this.name}.`);
  }
};

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

Object.assign(Person.prototype, sayNameMixin);

const person = new Person('John');
person.sayName(); // Output: My name is John.

In this example, mixin-based inheritance is used to add additional functionality to a class. The sayNameMixin object contains a sayName method. The Person class does not have the sayName method, but it is added to its prototype using Object.assign(Person.prototype, sayNameMixin). This way, instances of the Person class can access the sayName method as if it were part of the class itself.


Feel free to copy the code and experiment with our javascript compiler


Output:

×