does javascript support multiple inheritance like C++

ぐ巨炮叔叔 提交于 2019-11-28 12:47:31

Technically, JavaScript does not offer multiple inheritance. Each object has a well-defined single "prototype" object, and thus a "prototype chain".

However, it is possible to augment any object with additional methods, so-called "expandos". So you could iterate over a collection of methods and individually add them to newly created objects. Such a collection is called "mixin".

Several frameworks offer mixins, for example:

  • qooxdoo
  • ExtJS
  • mootools
  • ...

They all work pretty much the same.

Note however that this is not real inheritance, since changes to the mixin will not be reflected in the objects.

For example:

var mixin = {
    method: function () {
        console.log('Hello world!');
    }
};
var foo = new fun1();
foo.method = mixin.method;
foo.method(); // Hello world!
mixin.method = function () { console.log('I changed!') };
foo.method(); // Hello world!

Javascript supports mixins which are (in my opinion) way better than C++ multiple inheritance. One has to change the thinking from the C++ way to appreciate how useful mixins can be. You can read about them:

Fresh Look at Mixins

Wikipedia Mixins

As many references as you want to read

Well you could simply have fun2 inherit from fun1 to begin with.

fun2.prototype = new fn1;

If the above doesn't work for you, then unfortunately you can't do live multiple inheritance. You could copy the properties over to the the new Object, but then it isn't really 'live' inheritance.

For Example:

func3.prototype = new fun1();
for(var i in func2.prototype)func3.prototype[i]=fun2.prototype[i];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!