How to get all objects of this type in javascript

I want to get all objects (not DOM elements) of a given type created using the new key.

Is it possible?

function foo(name) { this.name = name; } var obj = new foo(); 

How to get a link to all foo objects?

+4
source share
2 answers

If they were all assigned in the global scope, and you don't need to check iframe / window borders, and you don't need to do this in IE (for example, 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 kind of functions created inside functions somewhere, in which case they are not available.

You can try changing the constructor before instantiating:

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

There is no built-in way to do this, however you can easily create a foo constructor to store an array of created objects.

 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}] 
+14
source

All Articles