2010-04-08 124 views

回答

5

如果它们全部在全局范围内分配,并且不需要跨越边界进行检查,并且不需要在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) 
    } 
} 

Buuuuut你可能有一些FOOS内某处函数实例化,在这种情况下,他们是不可用的。

你或许可以尝试之前实例修改构造函数:

var fooObjects = []; 
var oldFoo = window.foo; 
window.foo = function() { 
    fooObjects.push(this); 
    return oldFoo.apply(this, arguments); 
} 

foo.prototype = oldFoo.prototype; 
14

没有内置的方式做到这一点,但是,你可以轻松拥有您的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}] 
+0

谢谢你的快速回答。我选择了其他答案,因为它提供了一种获取对象而不更改构造函数(尽管不完美)的方法。 – FKDev 2010-04-09 08:55:32

相关问题