假设我有一个函数:
function Control(value){
var self=this;
self.param1=value;
self.param2=value.text;
}
是否可以在 JavaScript 中获取该函数创建的所有实例?
最佳答案
如果不修改类,您几乎无能为力。如果您可以修改它,只需保留您构造的每个实例的引用即可:
function Control(value){
Control.instances = Control.instances || [];
Control.instances.push(this);
var self=this;
self.param1=value;
self.param2=value.text;
}
// In case you are worried about garbage collection
Control.prototype.destroy = function() {
var index = Control.instances.indexOf(this);
Control.instances.splice(index, 1);
}
// Usage:
var x = new Control();
var y = new Control();
// do stuff with x and y
console.log('There are ' + Control.instances.length + ' instances of Control');
// all done with x and y
x.destroy();
x = null;
y.destroy();
y = null;
// no more references to the two instances, they can be garbage collected
但请注意,您将阻止垃圾收集器释放您未调用 destroy() 的任何实例的内存。
关于类的 JavaScript 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19184048/