[英]JavaScript - Get all objects that are instances of a specific class
I am not sure it is possible but I will try my luck.我不确定这是否可能,但我会试试运气。
Is it possible in JavaScript to find all objects that are instances of a specific class?是否可以在 JavaScript 中找到作为特定类实例的所有对象?
For example:例如:
var obj1 = new MyClass();
var obj2 = new MyClass();
var obj3 = new MyClass();
I want to specify the class name "MyClass" and to get "obj1,obj2,obj3" in response .我想指定类名“MyClass”并在响应中获得“obj1,obj2,obj3” 。
How can I do that?我怎样才能做到这一点?
You can do it like this:你可以这样做:
function MyClass(){}; MyClass.prototype.test = function(){ console.log('TEST'); }; function MyClassFactory(){ this.instances = []; }; MyClassFactory.prototype.create = function(){ let tmp = new MyClass(); this.instances.push(tmp); return tmp; }; MyClassFactory.prototype.get = function(i){ return this.instances[i]; }; MyClassFactory.prototype.getAll = function(){ return this.instances; }; let factory = new MyClassFactory(); let obj1 = factory.create(); let obj2 = factory.create(); let obj3 = factory.create(); let test1 = factory.get(0); let test2 = factory.getAll(); for(let t of test2){ t.test(); } test1.test();
As far as I know, this doesn't work.据我所知,这行不通。 You could save your objects in an array and iterate over it to retrieve all objects of class
MyClass
.您可以将对象保存在一个数组中并对其进行迭代以检索
MyClass
类的所有对象。
var objects = [new MyClass(), new MyClass(), new MyClass()];
function getObjectsOfClass(objects, clazz) {
var objArr = [];
for (var i = 0; i < objects.length; i++) {
if (objects[i] instanceof clazz) {
objArr.push(objects[i];
}
}
return objArr;
}
Imagine this situation.想象一下这种情况。
function M(){}
var m = new M();
Then you van do something like然后你做一些类似的事情
for(let f in window){ if(window[f] instanceof M){console.log("founded"+f);}}
And you will find your object.你会找到你的对象。
Hope that helps希望有帮助
You can only if you made some modification to the constructor只有对构造函数进行了一些修改,您才能
example:例子:
var MyClassInstances = [];
var MyClass = function() { //constructor
MyClassInstances.push(this); //push the new instance
}
thats it!.就是这样!。 But be aware that it might become memory leak.
但请注意,它可能会成为内存泄漏。 so, you have to remove the reference from MyClassInstances when the objects are not needed.
因此,当不需要对象时,您必须从 MyClassInstances 中删除引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.