JavaScript では、プロトタイプの継承を 1 回だけ実行できます。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/