Javascript 检查是否存在类的任何实例

Javascript 检查是否存在类的任何实例,javascript,Javascript,有没有办法检查给定类是否有实例 如果有办法-也可以检索这些实例吗?将每个实例添加到构造函数中的数组中: Abc类{ 构造函数(arg){ this.arg=arg; Abc.instances.push(这个); } } Abc.instances=[]; 新Abc(“qwe”); 新Abc(“rty”); console.log(Abc.instances)将每个实例添加到构造函数中的数组中: Abc类{ 构造函数(arg){ this.arg=arg; Abc.instances.pus

有没有办法检查给定类是否有实例


如果有办法-也可以检索这些实例吗?

将每个实例添加到构造函数中的数组中:

Abc类{
构造函数(arg){
this.arg=arg;
Abc.instances.push(这个);
}
}
Abc.instances=[];
新Abc(“qwe”);
新Abc(“rty”);

console.log(Abc.instances)将每个实例添加到构造函数中的数组中:

Abc类{
构造函数(arg){
this.arg=arg;
Abc.instances.push(这个);
}
}
Abc.instances=[];
新Abc(“qwe”);
新Abc(“rty”);

console.log(Abc.instances)Abc中删除之前,
Abc
的任何实例都不会被删除和垃圾收集。实例
我会接受这个答案,因为我的问题似乎没有不同的解决方案换句话说,唯一可以做到这一点的方法是,如果您编写类来存储这些信息,请注意,这并不是OP真正要求的。这是一个有先决条件的解决方案。小心,这是一个潜在的内存泄漏。
Abc
的任何实例在您从
Abc中删除之前都不会被删除和垃圾收集。实例
我会接受这个答案,因为我的问题似乎没有不同的解决方案。您的用例是什么?我的代码的某些部分应该根据是否存在类实例而改变其行为。如果它能够准确地知道这些实例是什么类型的,那么之后就可以调整行为,那就更好了。您的用例是什么?我的代码的某些部分应该根据类的实例是否存在而改变其行为。如果它能够确切地知道这些是什么样的情况,这样以后就可以调整行为,那就更好了。
class Instance{
  constructor(...args){
   //doSomething for init;
   Instance.HAS.add(this);
 }

}
Instance.HAS={
  instances:[],
add(instance){
this.instances.push(instance);
},
has(instance){
return this.instances.indexOf(instance)>-1;
},
all(){
 return this.instances;
}
};

let i1 = new Instance();
let i2 = new Instance();

console.info(Instance.HAS.all());
//VM1164:1 (2) [Instance, Instance]
console.info(Instance.HAS.has(i1));
//VM1245:1 true