3

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?

1 Answer 1

6

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
Sign up to request clarification or add additional context in comments.

3 Comments

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.
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]; } };
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.