Javascript

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"

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s