2010-04-08 46 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

相關問題