I thought there would already be an answer for this but I can't seem to find one.. How can I run a particular class method on all instances of this class in Javascript?
This has to be done in a situation where I do not know the names of the instances. I think I could use some sort of static variable inside my class to store all instances, but this doesn't seem to exist in JS
So how to call my method on all existing instances of my class? Note : just for clarification : I'm not speaking about CSS classes, I'm speaking about objects.
Edit : By Class in Javascript, I mean the creation of a new object on a function:
function something()
{
}
var instance = new something();
You'll have to provide a custom implementation.
I would do something like this :
Or like this :
Then you could loop through all instances like so :
You'll need to store a list of instances yourself:
If memory leaks are a concern then you can create a method for deleting instances when you are done with them:
Sorry for such a late reply, but I found myself trying to achieve this and I think this may be a simpler answer.
Say you want all instances of class MyClass, only get instances created at top window level (not including instances created inside a closure):
You can create a static array and store it on your constructor function:
However, you need some way to figure out when to remove instances from this array, or you'll leak memory.
In Chrome 62+ you can use
queryObjects
which will not work in native JavaScript code but in the console so is great for debugging.