javascript是否支持C ++等多重继承 [英] does javascript support multiple inheritance like C++
问题描述
我知道如何在javascript中继承,但我只能继承一个对象。
例如。
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() {
...
...
};
}
现在如果我想要 fun3
继承对象 fun1
对象我可以这样做
now if i want an fun3
object to inherit fun1
object i can do this
fun3.prototype=new fun1();
或继承 fun2
我可以做的对象这个
or to inherit fun2
object i can do this
fun3.prototype=new fun2();
但我怎样才能继承 fun1
和 fun2
?
推荐答案
从技术上讲,JavaScript不提供多重继承。每个对象都有一个明确定义的单个原型对象,因此是一个原型链。
Technically, JavaScript does not offer multiple inheritance. Each object has a well-defined single "prototype" object, and thus a "prototype chain".
但是,可以用其他方法扩充任何对象,所以 - 称为expandos。因此,您可以迭代一组方法,并将它们单独添加到新创建的对象中。这样的集合称为mixin。
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".
几个框架提供mixins,例如:
Several frameworks offer mixins, for example:
- qooxdoo
- ExtJS
- mootools
- ...
- qooxdoo
- ExtJS
- mootools
- ...
它们的工作方式基本相同。
They all work pretty much the same.
但请注意,这不是真正的继承,因为更改mixin不会反映在对象中。
Note however that this is not real inheritance, since changes to the mixin will not be reflected in the objects.
例如:
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是否支持C ++等多重继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!