Skip to content

JavaScript extend multiple classes | Code

  • by

Use the Mix-ins concept to extend multiple classes in JavaScript. A JS class can only have a single superclass, so multiple inheritances from child classes are not possible. The functionality must be provided by the superclass.

A function with a superclass as input and a subclass extending that superclass as output can be used to implement mix-ins.

let calculatorMixin = Base => class extends Base {
  calc() { }
};

let randomizerMixin = Base => class extends Base {
  randomize() { }
};

A class that uses these mix-ins can then be written like this:

class Foo { }
class Bar extends calculatorMixin(randomizerMixin(Foo)) { }

JavaScript extends multiple classes

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script>
    class Parent {
      someParentMethod () {
       console.log('Parent')
     }
   }

   class ChildOne extends Parent {
     someChildOneMethod () {
       console.log('someChildOneMethod')
     }
   }

   class ChildTwo extends Parent {
     someChildTwoMethod () {
       console.log('someChildTwoMethod')
     }
   }


    // define GrandChild as a Mix-in:
    let GrandChild = Base => class extends Base {
      someGrandChildMethod() {
       console.log('someGrandChildMethod')
     }
   };

    //Then:
    class GrandChildOne extends GrandChild(ChildOne) { }
    class GrandChildTwo extends GrandChild(ChildTwo) { }

    const grandChildOne = new GrandChildOne()
    const grandChildTwo = new GrandChildTwo()

    grandChildOne.someChildOneMethod();
    grandChildTwo.someChildTwoMethod();

  </script>

</body>
</html> 

Output:

Another approach is using composition, where you create separate classes for different functionalities and then compose them within your main class. Here’s an example:

class Engine {
  start() {
    console.log('Engine started');
  }

  stop() {
    console.log('Engine stopped');
  }
}

class MusicPlayer {
  play() {
    console.log('Playing music');
  }

  stop() {
    console.log('Music stopped');
  }
}

class Car {
  constructor() {
    this.engine = new Engine();
    this.musicPlayer = new MusicPlayer();
  }

  startEngine() {
    this.engine.start();
  }

  stopEngine() {
    this.engine.stop();
  }

  playMusic() {
    this.musicPlayer.play();
  }

  stopMusic() {
    this.musicPlayer.stop();
  }
}

const myCar = new Car();
myCar.startEngine(); // Output: Engine started
myCar.playMusic();   // Output: Playing music

In this example, the Car class contains instances of the Engine and MusicPlayer classes, allowing you to compose functionality without directly extending multiple classes.

Do comment if you have any doubts or suggestions on this JS class topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *