Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 views
in Technique[技术] by (71.8m points)

how to get all objects of a given type in 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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...