Reputation: 497
What is the best way to fire a method in many children by calling the parent's method?
For example, lets say I have a parent object Foo which has many instances: BarX, BarY, etc.
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;
Is there any easy way to fire off the move function in all instances? Am I limited to looping through the instances and firing off the function like that or can I somehow fire the function in Foo and have it trickle down and fire off all instances who extend Foo?
Upvotes: 0
Views: 92
Reputation: 29831
No. But you could be more clever about it. Make a static moveAll
function on Foo
. Examples make things clearer. 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();
Upvotes: 3