How to Extend Two Classes in JavaScript?

Estimated read time 2 min read

JavaScript does not support multiple inheritance, which means you cannot extend two classes at the same time. However, you can use a technique called “mixins” to combine the functionality of two or more classes into a single class. Here’s an example of how to use mixins in JavaScript:

// Define the first class
class Animal {
  constructor(name) {
    this.name = name;
  }
  
  speak() {
    console.log(`${this.name} makes a noise.`);
  }
}

// Define the second class
class Canine {
  bark() {
    console.log(`${this.name} barks.`);
  }
}

// Define a mixin that combines the two classes
let mix = (superclass) => class extends superclass {
  constructor(...args) {
    super(...args);
  }
  
  speak() {
    super.speak();
    console.log(`${this.name} growls.`);
  }
  
  bark() {
    super.bark();
    console.log(`${this.name} growls.`);
  }
}

// Create a new class that uses the mixin
class Dog extends mix(Animal, Canine) {
  constructor(name) {
    super(name);
  }
}

// Test the new class
let dog = new Dog('Fido');
dog.bark(); // output: Fido barks. Fido growls.
dog.speak(); // output: Fido makes a noise. Fido growls.

In the above example, we define two classes Animal and Canine. We then define a mixin that combines the functionality of both classes. The mix function takes a superclass argument and returns a new class that extends superclass and includes the methods from both Animal and Canine. Finally, we define a new class Dog that uses the mix function to combine the functionality of Animal and Canine. We can then create instances of Dog and call the methods from both Animal and Canine.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply