开发者

how to get all objects of a given type in javascript

开发者 https://www.devze.com 2022-12-25 22:35 出处:网络
I want to retrieve all objects (not DOM elements) 开发者_JS百科of a given type created with the \"new\" keyword.

I want to retrieve all objects (not DOM elements) 开发者_JS百科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 ?


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}]


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;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号