Vincent Duprez Vincent Duprez -5 years ago 145
jQuery Question

Get all instances of class in jquery or js

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();

Answer Source

You can create a static array and store it on your constructor function:

MyClass.allInstances = [];

However, you need some way to figure out when to remove instances from this array, or you'll leak memory.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download