我想检索所有使用“new”关键字创建的特定类型的对象(而不是DOM元素)。
这是否可能?
如何检索所有foo对象的引用?
这是否可能?
function foo(name)
{
this.name = name;
}
var obj = new foo();
如何检索所有foo对象的引用?
function foo(name)
{
this.name = name;
}
var obj = new foo();
没有内置的方法可以实现这一点,但是您可以轻松地让您的foo
构造函数存储一个已创建对象的数组。
function foo(name)
{
this.name = name;
foo.objects.push(this);
}
foo.objects = [];
foo.prototype.remove = function() {
for (var i=0; i<foo.objects.length; i++) {
if (foo.objects[i] == this) {
foo.objects.splice(i,1);
}
}
};
for (var i=0; i<10; i++) {
var obj = new foo();
obj.test = i;
}
// lets pretend we are done with #5
foo.objects[5].remove();
console.log(foo.objects);
// [Object { test=0}, Object { test=1}, Object { test=2}, Object { test=3},
// Object { test=4}, Object { test=6}, Object { test=7}, Object { test=8},
// Object { test=9}]
如果它们都在全局作用域中分配,并且您不需要跨iframe
/window
边界进行检查,也不需要在IE中执行此操作(例如,您只是试图调试某些内容),则应该能够遍历全局作用域:
var fooObjects = [];
for(var key in window) {
var value = window[key];
if (value instanceof foo) {
// foo instance found in the global scope, named by key
fooObjects.push(value)
}
}
但是你可能在某些函数内部实例化了一些foos,这样它们就不可用了。
你可以尝试在实例化之前修改构造函数:
var fooObjects = [];
var oldFoo = window.foo;
window.foo = function() {
fooObjects.push(this);
return oldFoo.apply(this, arguments);
}
foo.prototype = oldFoo.prototype;