How to Implement Multiple Inheritance in Object-Oriented JavaScript?

Estimated read time 1 min read

Multiple inheritance is not natively supported in JavaScript, but there are several ways to achieve similar behavior:

  1. Mixins: A mixin is a simple way to reuse a class’s methods in another class without inheritance. You can create a mixin function that takes the target class as an argument and adds the methods from the mixin to the target class.
  2. Composition: In composition, instead of inheriting properties and methods, an object contains other objects. Each object can be used to provide specific functionality and can be composed in any number of ways to build up the required functionality.
  3. Class factory: A class factory is a function that generates classes. The class factory can take multiple classes as arguments and return a new class that combines the functionality of the original classes.

Here is an example of how to use mixins to implement multiple inheritance:

function Loggable(baseClass) {
  return class extends baseClass {
    log() {
      console.log(`Log: ${this.toString()}`);
    }
  };
}

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

  toString() {
    return `Person: ${this.name}`;
  }
}

class Employee extends Loggable(Person) {
  constructor(name, title) {
    super(name);
    this.title = title;
  }

  toString() {
    return `Employee: ${this.name} (${this.title})`;
  }
}

const employee = new Employee('John', 'Manager');
employee.log(); // Log: Employee: John (Manager)

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply