Multiple inheritance in Javascript
This posts gives a short code sample on how to implement multiple inheritance in Javascript.
function multi() {
var n = {},
stuff, j = 0,
len = arguments.length;
for (j = 0; j < len; j++) {
stuff = arguments[j];
for (vari in stuff) {
if (stuff.hasOwnProperty(i)) {
n[i] = stuff[i];
}
}
}
return n;
}
//Use the multi() function to implement multiple inheritance
var shape = {
name: 'Shape',
toString: function() {
return this.name;
}
};
vartwoDee = {
name: '2D shape',
dimensions: 2
};
var triangle = multi(shape, twoDee, {
name: 'Triangle',
getArea: function() {
return this.side * this.height / 2;
},
side: 5,
height: 10
});
//Now run the code
>triangle.getArea();
25
>triangle.dimensions;
2
>triangle.toString();
"Triangle"