Reputation: 33587
Let's say I have some class called loopObject
and I initialize every object through something like var apple = new loopObject();
Is there anyway to loop through all objects of a class so that some function can be performed with each object as a parameter? If there isn't a direct method, is there a way to place each new object into an array upon initialization?
Upvotes: 1
Views: 2735
Reputation: 33587
var allObjects [] = new Array();
function loopObject() {
...
allObjects.push(this);
}
Then one can loop through all elements of allObjects
as necessary using allObjects.length
.
Upvotes: 0
Reputation: 186662
function loopObject(){
this.name = 'test'
};
var list = [], x = new loopObject, y = new loopObject;
list.push(x)
list.push(y)
for ( var i = list.length; i--; ) {
alert( list[i].name )
}
Upvotes: 1
Reputation: 887777
You can make an array that contains every instance, like this:
function LoopObject() {
LoopObject.all.push(this);
}
LoopObject.all = [];
However, it will leak memory - your instances will never go out of scope.
Upvotes: 2