Implement multiple inheritance in Javascript

别等时光非礼了梦想. 提交于 2019-11-30 16:19:59

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.

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