在 Javascript 中获取类的所有实例 [英] Get all instances of class in Javascript

查看:69
本文介绍了在 Javascript 中获取类的所有实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以为已经有答案了,但我似乎找不到.如何在 Javascript 中对此类的所有实例运行特定的类方法?

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.

Javascript中的类,我的意思是在函数上创建一个新对象:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆