I have observed that through the use of "prototype" property in Javascript (and indirectly setting up the prototype chain), one can implement multi-level inheritance in JavaScript. But is it possible to implement multiple inheritance in Javascript by some way? Any simple examples would be great.
To implement simple inheritance you usually do
MyClass.prototype = new MySuperClass();
but you could also copy the content of another "class" :
MyClass.prototype = new MySuperClass();
var myOtherSuperClass = new MyOtherSuperClass();
for (var key in myOtherSuperClass) {
MyClass.prototype[key] = myOtherSuperClass[key];
}
Of course you could use an utility like jQuery.extend to do that, or roll your own.
A limit is that instanceof
won't detect MyOtherSuperClass
.
Just to be clear, JS doesn't have multiple inheritance.
Each object can only have one prototype.
However, since EVERYTHING is mutable, it can support "mixins", which is what the extend methods are all about. They just copy the keys of one object to another. That's not actually inheritance, though. Usually, in that scheme, the resultant object will only have the one proto, which is Object.
It's possible to implement multiple inheritance in JavaScript, although very few libraries does it. The only example I know is Ring.js.
Of course it doesn't rely only on prototypes, so instanceof
doesn't work. But the library provides a replacement for it so it's not a big deal.
来源:https://stackoverflow.com/questions/15473369/implement-multiple-inheritance-in-javascript