Skip to content

Multiple inheritances in JavaScript

  • by

There are no Multiple inheritances in JavaScript. In JavaScript every object has a single associated prototype, it cannot dynamically inherit from more than one prototype chain.

Inheriting from two classes can be done by creating a parent object as a combination of two parent prototypes.

The syntax for subclassing makes it possible to do that in the declaration since the right-hand side of the extends clause can be any expression. Thus, you can write a function that combines prototypes according to whatever criteria you like, and call that function in the class declaration.

Multiple inheritances in JavaScript

Simple example code creating a new prototype with the methods of two other prototypes.

<!DOCTYPE html>
<html>
<body>
  <script>
    var Animal = function() {
      this.className = 'Animal';
      this.vector = {x: 0, y: 0};
    }
    var Flying_object = function() {
      this.className = 'Flying_object';
      this.value = 'some value';
    }

    function mix(classA, classB) {
      var instanceA = new classA(),
      instanceB = new classB();
      for (var prop in instanceA) {
        instanceB[prop] = instanceA[prop];
      }
      return instanceB;
    }

    var Bird = function() { this.className = 'Bird'; };
    Bird.prototype = mix(Animal, Flying_object);
    var instance = new Bird();

    console.log(instance);
    console.log(instance.className);
    console.log(instance.value);
  </script>

</body>
</html> 

Output:

Multiple inheritances in JavaScript

Source: stackoverflow.com

Do comment if you have any doubts or suggestions on this JS inheritance 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 *