Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
138
rated 0 times [  141] [ 3]  / answers: 1 / hits: 15720  / 14 Years ago, thu, april 8, 2010, 12:00:00

I want to retrieve all objects (not DOM elements) of a given type created with the new keyword.



Is it possible ?



function foo(name)
{
this.name = name;
}

var obj = new foo();


How can I retrieve a reference to all the foo objects ?


More From » javascript

 Answers
74

If they were all assigned in the global scope, and you don't need to check across iframe/window boundaries, and you do not need to do this in IE (eg you're just trying to debug something), you should be able to iterate over the global scope:



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 you probably have some foos instantiated inside functions somewhere, in which case they're not available.



You can perhaps try modifying the constructor prior to instantiations:



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

foo.prototype = oldFoo.prototype;

[#97129] Monday, April 5, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
parker

Total Points: 259
Total Questions: 109
Total Answers: 97

Location: Zambia
Member since Thu, Jun 25, 2020
4 Years ago
;