通过调用父级方法来触发许多子级中的方法的最佳方法是什么?
例如,假设我有一个父对象 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 的实例吗?
最佳答案
没有。但你可以做得更聪明。在 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();
关于javascript - 通过触发父方法来触发实例方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4493518/