Multiple inheritance

Multiple inheritance is where a child inherits from more than one parent. Some OO languages support multiple inheritance out of the box and some don't. You can argue both ways, that multiple inheritance is convenient or that it's unnecessary, complicates application design, and it's better to use an inheritance chain instead. Leaving the discussion of multiple inheritance's pros and cons for the long, cold winter nights, let's see how you can do it in practice in JavaScript.

The implementation can be as simple as taking the idea of inheritance by copying properties and expanding it so that it takes an unlimited number of input objects to inherit from.

Let's create a multi() function that accepts any number of input objects. You can wrap the loop that copies properties in another loop that goes through all the objects passed as arguments to the function:

    function multi() { 
      var n = {}, stuff, j = 0, len = arguments.length; 
      for (j = 0; j <len; j++) { 
        stuff = arguments[j]; 
        for (var i in stuff) { 
          if (stuff.hasOwnProperty(i)) { 
            n[i] = stuff[i]; 
          } 
        } 
      } 
      return n; 
    } 

Let's test this by creating three objects-shape, twoDee, and a third, unnamed object. Then, creating a triangle object means calling multi() and passing all three objects:

    var shape = { 
      name: 'Shape', 
      toString: function () { 
        return this.name; 
      } 
    }; 
 
    var twoDee = { 
      name: '2D shape', 
      dimensions: 2 
    }; 
 
    var triangle = multi(shape, twoDee, { 
      name: 'Triangle', 
      getArea: function () { 
        return this.side * this.height / 2; 
      }, 
      side: 5, 
      height: 10 
    }); 

Does this work? Let's see. The getArea() method should be an own property, dimensions should come from twoDee, and toString() should come from shape:

    >triangle.getArea(); 
    25 
    >triangle.dimensions; 
    2 
    >triangle.toString(); 
    "Triangle" 

Bear in mind that multi() loops through the input objects in the order they appear and if it happens that two of them have the same property, the last one wins.

Mixins

You might come across the term mixin. Think of a mixin as an object that provides some useful functionality but is not meant to be inherited and extended by subobjects. The approach to multiple inheritance outlined previously can be considered an implementation of the mixins idea. When you create a new object, you can pick and choose any other objects to mix into your new object. By passing them all to multi(), you get all their functionality without making them part of the inheritance tree.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.154.41