Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

does javascript support multiple inheritance like C++

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...