Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
5
rated 0 times [  11] [ 6]  / answers: 1 / hits: 28721  / 11 Years ago, tue, october 22, 2013, 12:00:00

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

More From » class

 Answers
34

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



MyClass.allInstances = [];
MyClass.allInstances.push(this);


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


[#74802] Monday, October 21, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
donovanjasek

Total Points: 465
Total Questions: 103
Total Answers: 113

Location: Saint Vincent and the Grenadines
Member since Thu, Oct 15, 2020
4 Years ago
;