Implement multiple inheritance in Javascript

回眸只為那壹抹淺笑 提交于 2019-11-29 23:19:25

问题


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.


回答1:


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.




回答2:


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.




回答3:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!