获取JavaScript中所有类的实例 [英] Get all instances of class in Javascript
问题描述
我以为已经有了答案,但是似乎找不到答案。.
如何在Java中对该类的所有实例运行特定的类方法?
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?
必须在我不知道实例名称的情况下执行此操作。
我想我可以在类中使用某种静态变量来存储所有实例,但这在JS中似乎不存在
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
所以在类的所有现有实例上调用我的方法?
注意:只是为了澄清:我不是在讲CSS类,而是在讲对象。
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.
编辑:按Java类讲,我的意思是在函数上创建新对象:
Edit : By Class in Javascript, I mean the creation of a new object on a function:
function something()
{
}
var instance = new something();
推荐答案
您可以创建一个静态数组并将其存储在您的构造函数:
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.
这篇关于获取JavaScript中所有类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!