Reputation: 989
Let's say I have the following:
function FooBar (s) {
this.s = s;
this.logS = function () { console.log(this.s)}
}
var Foo = new FooBar('foo');
var Bar = new FooBar('bar');
My goal is to call .logS()
for every instance of FooBar
. I can do this by calling them individually:
Foo.logS();
Bar.logS();
But let's say I do not know the names of all the objects of type FooBar - is there a method to execute all of them? For example, in principle I want to have this line of code: FooBar.logS()
equate to calling Foo.logS()
and Bar.logS()
.
Well that obviously doesn't work, but I'm looking for something like that in principle. Failing that, is there a way to get a list of names of all objects that are instanceof FooBar?
For example, I can do this:
for (var o in window) {
if (window[o] instanceof FooBar) {
window[o].logS();
}
}
But that only works for objects directly under window
. If I were to say do this...
var bazs = [new FooBar('baz')];
...the loop wouldn't work. I suppose I could make a function to recursively walk through window
but I think at best that would be slow but may not even find all of them (maybe?)
TL;DR
The goal is to find every object
where (object instanceof FooBar)
regardless of where object
nested within window
Possible?
Edit: Clarification
I apologize, it seems I was not being clear enough. The suggested methods for keeping track of instances as they are created are great (array, subscription), but it's not what I need.
More detailed scenario. There is a 3rd party script that is used multiple times throughout a webpage. I get to insert my own code at the bottom of the page. So, I do not get to alter FooBar to keep track of things from the get-go, before any instances of it are created. So my code needs to find all instances of FooBar that already exist when my code is executed.
Upvotes: 2
Views: 1509
Reputation: 816462
You could make so that creating a new instance of FooBar
adds that instance to an array. E.g.:
function FooBar() {
FooBar.instances.push(this);
// ...
}
FooBar.instances = [];
FooBar.logS = function() {
FooBat.instances.forEach(function(instance) {
instance.logS();
});
};
Alternatively you could implement an event handling or publish/subscriber system where each instance of FooBar
listens to a specific event, which you then simply trigger. E.g.
function FooBar() {
// ...
Arbiter.subscribe('logS', this.logS.bind(this));
}
Arbiter.inform('logS');
If you don't want to implement something like this on your own, there are existing libraries out there, e.g. https://github.com/mroderick/PubSubJS
Upvotes: 2