2016-05-13 4 views
1

を持つ親からの多重継承は、複数のクラスのプロトタイプを継承するJavaScriptでの方法があります:プロトタイプ

は、ex

function food(){ 
} 

food.prototype.eat = function(){} 

function plant(){ 
} 

plant.prototype.grow = function(){} 


function tomato(){ 
} // needs to have grow and eat methods (and if possible in proto type) 

編集:

なしトマトは食べない、 食べる方法は、食べ物があなたを食べるものではなく、食べ物を食べることを意味します。

+1

キラートマトの攻撃に基づいてゲームを実装していますか? https://en.wikipedia.org/wiki/Attack_of_the_Killer_Tomatoes :) –

答えて

1

トマトが何かを食べる理由はわかりません:)

しかし、JavaScriptで何らかの多重継承を実装することは可能です。あなたは、両方の親オブジェクトのプロトタイプからプロパティを取ることによって、プロトタイプを拡張する必要があります。

function Plant(name) { 
 
    this.name = name; 
 
} 
 
Plant.prototype.grow = function() { 
 
    document.write("<pre>" + this.name + " growing </pre>"); 
 
}; 
 

 
function Killer(name) { 
 
    this.name = name; 
 
} 
 
Killer.prototype.eat = function() { 
 
    document.write("<pre>" + this.name + " eating </pre>"); 
 
}; 
 

 
function Tomato(name) { 
 
    this.name = name; 
 
} 
 

 
for (var key in Plant.prototype) { 
 
    Tomato.prototype[key] = Plant.prototype[key]; 
 
} 
 

 
for (var key in Killer.prototype) { 
 
    Tomato.prototype[key] = Killer.prototype[key]; 
 
} 
 

 
var killerTomato = new Tomato("yum-yum"); 
 

 
killerTomato.eat(); 
 
killerTomato.grow();

+0

forループの代わりにforeachメソッドを使用できますか? –

+0

foreachはどういう意味ですか? for(var ... in)は、配列を持つようにオブジェクト –

+0

をループする標準的な方法です [0,2,4,5] .foreach(function(e){}) –

1

もう一つの方法は、Object.assign()メソッドを使用してされるだろう。

function food(){ 
    this.value_a = 1; 
} 
food.prototype.eat = function(){ 
    console.log("eats"); 
} 

function plant(){ 
    this.value_b = 2; 
} 

plant.prototype.grow = function(){ 
    console.log("grows"); 
} 

function tomato(){ 
    food.call(this); 
    plant.call(this); 
    this.value_c = 3; 
} 


Object.assign(tomato.prototype, food.prototype); 
Object.assign(tomato.prototype, plant.prototype); 

var new_tomato = new tomato(); 
console.log(new_tomato) 
+0

上記と同じ溶液が、他の割り当て方法について 感謝を行うことができますが、私はまた私が使用するつもりだったとコメントobject.assign、まだthx –

+0

ええ、拡張している各クラスのコンストラクタを呼び出すことを忘れないでください。そうしないと、クラスの初期化中に評価するはずのすべてのプロパティが失われます。 – Alexus