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:

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 *