Multiple inheritance in JavaScript



JavaScript is a partially object-oriented language. To work with this, the object-oriented nature needs to be understood. In this article, we are going to focus on the multiple inheritance concept inside JavaScript.

An object can be inherited from multiple other objects, i.e. the object has common property from other parent objects not only a single parent. In JavaScript, this can be achieved by merging properties from different properties into one single object. Let us see the overall syntax which represents how multiple properties can be merged.

Syntax

Let us consider a function syntax like the below −

function multiple(...arguments) {
   let objects = {};
   for (all arg of arguments) {
      objects = {
         ...object,
         ...arg
      };
   }
   return objects;
}

The above syntax can be used like−

const objects = multiple(
   { foo: 1 },
   { bar: 2 },
   { baz: 3 }
);

So we can pass multiple objects and then copy the properties by using the spread operator. Similar work can be done using mixins. Mixins are some objects that can be incorporated into some other objects. While creating an object, we can select which mixin will be incorporated into the final object.

Parasitic Inheritance

Another special form of inheritance is Parasitic Inheritance. In this type of inheritance, we take all the functionality from a few objects and turn them into a single object by taking all. The following example will illustrate this concept −

Example

<!DOCTYPE html> <html> <head> <title>HTML Console</title> </head> <body> <h3> Output Console </h3> <p> Output: </p> <div id="output"> </div> <div id="opError" style="color : #ff0000"> </div> <script> var content = '' var error = '' var opDiv = document.querySelector('#output') var opErrDiv = document.querySelector('#opError') // actual javascript code try { function object(my_proto) { function F() { } F.prototype = my_proto; return new F(); } const base2D = { name: '2D region', dimensions: 2 }; function rect(base2D, w, h) { const obj = object(base2D); obj.name = 'rectangle'; obj.calculateArea = function () { return this.width * this.height; }; obj.width = w; obj.height = h; return obj; } function circ(base2D, r) { const obj = object(base2D); obj.name = 'circle'; obj.calculateArea = function () { return 3.14159 * this.rad * this.rad; }; obj.rad = r; return obj; } const rectObj = rect(base2D, 5, 7); content += "The rectangle object: " + JSON.stringify(rectObj) + '<br>' content += "The area of rectangle: " + JSON.stringify(rectObj.calculateArea()) + '<br>' const circObj = circ(base2D, 10); content += "The circle object: " + JSON.stringify(circObj) + '<br>' content += "The area of the circle: " + JSON.stringify(circObj.calculateArea()) + '<br>' } catch (err) { error += err } finally { // display on output console opDiv.innerHTML = content opErrDiv.innerHTML = error } </script> </body> </html>

In this example, we have a function object() which returns an instance of function F. Then the base2D object is created which has a name and a dimension property. We can use this dimension property to check whether it is an appropriate type or not. And finally creating a rectangle object. The rectangle object is itself a 2D object and it has some of its properties. So, this object is taking the base2D object and width and height parameters. Another similar object circ is also created with a different set of parameters. The circle also falls under the 2d shape category so base2D property has been taken. But here the other parameter is the radius and its area calculating logic is different.

Constructor Borrowing

Another method to implement multiple inheritances is borrowing the constructors. In this approach, the parent constructor is used to form a child constructor. This can be illustrated by the following example −

Example

function CustomShape(id) { this.id = id; } CustomShape.prototype.name = 'Shape'; CustomShape.prototype.toString = function() { return this.name; }; function SquareShape(id, name, side) { CustomShape.apply(this, [id]); this.name = name; this.side = side; } SquareShape.prototype = new CustomShape(); SquareShape.prototype.name = 'Square'; function CircleShape(id, name, rad) { CustomShape.apply(this, [id]); this.name = name; this.rad = rad; } CircleShape.prototype = new CustomShape(); CircleShape.prototype.name = 'Circle';

In this example, the CustomShape parameter has the id property. We are calling the CustomShape constructor by calling apply function. Then we are creating two types. The square shape and CircleShape by assigning prototype of CustomShape object. The ‘name’ field is shared between all SquareShape objects as ‘Square’ and for all CircleShape objects a ‘Circle’

Conclusion

Multiple inheritance property takes multiple features from different objects and assigns them to the current object. In some pure object-oriented languages, we can assign multiple parent classes to some object so that they can take properties from these parent classes at once. In JavaScript, the idea is similar but the implementation approach is slightly different. JavaScript is not a completely object-oriented language so different approaches are applied to mimic the multiple inheritance features in the system.


Advertisements