User Tools

Site Tools


java-script:multiple-inheritance

This is an old revision of the document!


Java Script Multiple Inheritance

JavaScript does not support multiple inheritance directly, which means a class can't extend more than one class. The extends keyword can only be followed by a single class.
To incorporate functionality from multiple sources, JavaScript supports “mixins” as a way to accomplish this.

Java Script Mixins

A mixin is a class whose methods are intended to be added to (or “mixed in” to) other classes.

Example:

Person.js
class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
 
    description() {
        return `A person named ${this.name} who is ${this.age} years old`;
    }
}
 
class Animal {
    eats() {
        return `${this.name} eats.`;
    }
}
 
const AnimalMixin = Base => class extends Base {
    eats() {
        return `${this.name} eats.`;
    }
};
 
class Employee extends AnimalMixin(Person) {
    constructor(name, age, salary, jobTitle) {
        super(name, age);
        this.salary = salary;
        this.jobTitle = jobTitle;
    }
 
    description() {
        return `An employee is also ${super.description()}`;
    }
}
 
let employee = new Employee("Aurel", 30, 15000, "CEO boss");
console.log(employee.eats()); // Aurel eats.
console.log(employee.description()); // An employee is also A person named Aurel who is 30 years old

AnimalMixin is a function that takes a base class and returns a new class that extends the base class and adds the eats method. Then Employee extends AnimalMixin(Person) - effectively combining Person and Animal.

While mixins can be useful for sharing behavior between classes, they should be used sparingly as they can make code more complex and harder to follow. Also, note that super refers to the parent class, so calling super.description() in Employee will call description on Person, not Animal.

java-script/multiple-inheritance.1690387580.txt.gz · Last modified: 2023/07/26 19:06 by odefta