how to get all objects of a given type in javascript

后端 未结 2 1609
终归单人心
终归单人心 2020-12-09 22:56

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         


        
相关标签:
2条回答
  • 2020-12-09 23:22

    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 讨论(0)
  • 2020-12-09 23:30

    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}]
    
    0 讨论(0)
提交回复
热议问题