2010-12-20 44 views
0

通過調用父級方法在許多子級中觸發方法的最佳方法是什麼?通過觸發Parent方法觸發實例方法

例如,可以說我有其中有許多情況下,父對象的Foo:BarX,巴里等

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的孩子,他們是實例。 – 2010-12-20 20:25:10

+0

謝謝你的詞彙說明。固定在原來的文章。 – Empereol 2010-12-20 20:45:14

回答

3

不,但你可以更聰明一些。在Foo上製作靜態moveAll功能。例子使事情更清楚。 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();