does javascript support multiple inheritance like C++

匆匆过客 提交于 2019-12-17 20:27:37

问题


i know how to do inheritance in javascript but i can only inherit a single object. eg.

function fun1() {
this.var1=10;
this.meth1=function() {
...
...
};
}

function fun2() {
this.var2=20;
this.meth2=function() {
...
...
};
}

function fun3() {
this.var3=30;
this.meth3=function() {
...
...
};
}

now if i want an fun3 object to inherit fun1 object i can do this

fun3.prototype=new fun1();

or to inherit fun2 object i can do this

fun3.prototype=new fun2();

but how can i inherit both fun1 and fun2?


回答1:


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!



回答2:


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




回答3:


Here is an example of how to do that:

http://www.amirharel.com/2010/06/11/implementing-multiple-inheritance-in-javascript/




回答4:


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];


来源:https://stackoverflow.com/questions/6887828/does-javascript-support-multiple-inheritance-like-c

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