Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get all objects of a given type in javascript

Tags:

javascript

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 ?

like image 425
FKDev Avatar asked Apr 08 '10 19:04

FKDev


2 Answers

There is no built-in way to do that, however, you could easily have your foo constructor 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}]
like image 68
gnarf Avatar answered Sep 21 '22 06:09

gnarf


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;
like image 36
JPot Avatar answered Sep 20 '22 06:09

JPot