Multiple Inheritance

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) {
n[i] = stuff[i];
}
}
return n;
}



Let's test this by creating three objects: shape, twoDee and a third, unnamed object. Creating a triangle object will mean 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
});

Will it work? Let's see:

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

你可能感兴趣的:(inheritance)