是否有任何方法可以检查给定类的实例?
如果有办法-是否还可以检索这些实例?
答案 0 :(得分:5)
将每个实例添加到构造函数中的数组:
class Abc {
constructor(arg) {
this.arg = arg;
Abc.instances.push(this);
}
}
Abc.instances = [];
new Abc('qwe');
new Abc('rty');
console.log(Abc.instances);
答案 1 :(得分:0)
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