在 JavaScript 中,您可以只执行一次原型继承。您可以使用一些提供丰富类子系统的框架,例如ExtJS、Ember.js等。另一种方法可能是迭代所需对象的属性,然后将其应用于目标对象。像这样的东西:
function Node( desc ) {
this.desc = desc;
this.doNodeThing = function() {
console.log( "noding for " + this.desc );
}
}
function FooNode( desc ) {
this.desc = desc;
this.doFooNodeThing = function() {
console.log( "foo noding for " + this.desc );
}
}
function BarNode( desc ) {
this.desc = desc;
this.doBarNodeThing = function() {
console.log( "bar noding for " + this.desc );
}
}
function inherit( obj, superObj ) {
for ( var x in superObj ) {
if ( typeof superObj[x] == "function" ) {
obj[x] = superObj[x];
}
}
}
var n1 = new Node( "tree node" );
n1.doNodeThing();
var n2 = new Node( "folder node" );
n2.doNodeThing();
inherit( n1, new BarNode() );
n1.doBarNodeThing();
//n2.doBarNodeThing(); <= TypeError: n2.doBarNodeThing is not a function
inherit( n1, new FooNode() );
n1.doBarNodeThing();
n1.doFooNodeThing();
//n2.doFooNodeThing(); <= TypeError: n2.doFooNodeThing is not a function
上面的代码会将函数添加到对象本身,而不是原型。
jsFiddle:http: //jsfiddle.net/davidbuzatto/3cCGC/