2010-12-20 4 views
0

親メソッドを呼び出すことによって、多くの子プロセスでメソッドを起動する最善の方法は何ですか?例えば親メソッドを起動してインスタンスメソッドをトリガーする

、私は多くのインスタンスを持つ親オブジェクトはFooを持って言うことができます:などBARX、BarY、

Foo = function(){ 
    x = null; 
    y = null; 
    move = function(){ 
     x += 1; 
     y += 1; 
    }; 
} 

BarX = new Foo(); 
BarX.x = 50; 
BarX.y = 50; 

BarY = new Foo(); 
BarY.x = 200; 
BarY.y = 200; 

は、すべてのインスタンスに移動機能をオフに発射する簡単な方法はありますか?私はインスタンスをループしてそのような関数を実行することに限定していますか、何とかFooの関数を起動し、Fooを継承するすべてのインスタンスをトリックして起動できますか?

+0

ちょうどボキャブラリーノート:BarXとBarYはFooの子ではなく、インスタンスです。 –

+0

ボキャブノートをありがとう。元の投稿内で修正されました。 – Empereol

答えて

3

いいえ、あなたはもっと賢いかもしれません。 スタティックmoveAllFooに設定してください。例は物事をより明瞭にする。 Here is the fiddle

var Foo = function(x, y){ 
    this.x = x; 
    this.y = y; 
    this.move = function(){ 
     x += 1; 
     y += 1; 
     alert(x + ' ' + ' ' + y); 
    }; 
    Foo.instances.push(this); // add the instance to Foo collection on init 
}; 
Foo.instances = []; 
Foo.moveAll = function(){ 
    for(var i = 0; i < Foo.instances.length; i++) 
     Foo.instances[i].move(); 
} 

var a = new Foo(5, 6); 
var b = new Foo(3, 4); 

Foo.moveAll(); 
関連する問題