Object-oriented JavaScript
interface copying

Can JavaScript do multiple inheritance? Is it a good idea?

My answer to the first question is “I don’t think so—not as such”.

Regarding the second question: Some of the main objections to multiple inheritance in other languages such as C++ don’t exist in this context. Particularly, issues of casting a multiply-inherited object to be the type of one of its parents is very dangerous in C++, but JavaScript doesn’t even have types in that sense.

However, the use prototype-based inheritance rules out multiple inheritance as such. One might imagine using a closure to return a ParentB constructor that inherits from ParentA, but that will make all further ParentB’s inherit from ParentA. Then one might think to duplicate the ParentB constructor, then make the duplicate to inherit from ParentA, but then the heritage of the duplicate will no longer be that of ParentB, but of ParentA.

In the Java language, there is a mechanism for implementing an interface, separate from the inheritance mechanism. A few of lines of JavaScript can copy all the public members of an object to the current object. In the context of a language that allows members to be added on the fly, this is the analog to implementing an interface.

Start with two different parent classes, with some properties of the same name, and other properties not shared:




example: copying an interface

As before, use closures to create constructors that produce a different prototype function each time they are called.



The child sports properties of both parents; and those that had the same name in both parents take the value they had in the second parent. The constructor of the child indicates that it inherits from ParentA.

See

JavaScript Guide: Details of the Object Model

Javascript Closures

Richard Cornford, Private Static Members in Javascript, in Javascript Closures

JavaScript Closures for Dummies by Morris Johns