views:

46

answers:

1

Hi,

I know that I could do a simple prototypal inheritance in JavaScript like this:

var Parent = function() {
};

var Child = function() {
}

Child.prototype = new Parent();
Child.prototype.constructor = Child;

However, I'm curious to how one would accomplish deeper inheritances? What about multi-inheritance, is that possible?

+3  A: 

You can't do multiple inheritance in JavaScript. You can do deeper inheritance by simply going further:

var Parent = function() {};
var Child = function() {};
var InnerChild = function() {};

And to show it works:

Parent.prototype.x = 100;
Child.prototype = new Parent();
Child.prototype.y = 200;   
InnerChild.prototype = new Child();
InnerChild.prototype.z = 300;

var ic = new InnerChild();
console.log(ic.x); //prints 100, from Parent
console.log(ic.y); //prints 200, from Child
console.log(ic.z); //prints 300, from InnerChild, who only wants to express itself
Claudiu
Good answer. I'll add that while you can't do multiple inheritance, it's not hard to do a "mix-in" approach using, for example, the "extend" functions provided by libraries such as jQuery or underscore.js.
JacobM
I don't see how that isn't multiple inheritance (if you can do inheritance at all in javascript). Here is an extend function, that has the additional benefit of making the superclass method available:var extend = function (classObject, superClass) { for (var i in superClass.prototype) { if (classObject.prototype[i]) classObject.prototype["_super_" + i] = superClass.prototype[i]; else classObject.prototype[i] = superClass.prototype[i]; }};
rob
extend is kind of multiple inheritance, I suppose. It's not multiple inheritance really, though, it's "adding all the properties of one object to another". e.g. instanceof won't work properly. it's a fool's errand to apply OOP techniques to javascript anyway, though, as it's really prototype-inheritance. writing some code and saying "this is multiple inheritance" just confuses the issue.
Claudiu