views:

74

answers:

3

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?

+2  A: 

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.

SLaks
Why was this downvoted?
SLaks
Wouldn't reading the all array from the bottom and removing each item after use kill the instance and save memory?
faraz.yashar
@faraz: If you know when to kill it, yes. However, every time you call `new LoopObject()` and don't kill it, you'll leak. Remember to kill inside a `finally` block.
SLaks
@SLaks: Thanks a lot.
faraz.yashar
TypeError: Cannot call method 'push' of undefined on the line `LoopObject.all.push(this);`
faraz.yashar
@faraz: You forgot `LoopObject.all = [];` (Or you deleted or re-assigned it elsewhere)
SLaks
The empty square brackets causes a token error: "Uncaught SyntaxError: Unexpected token ]"
faraz.yashar
@faraz: `[]` is valid syntax for an array in all browsers. Please show me your exact code. Or, change it to `LoopObject.all = new Array();`
SLaks
+1  A: 
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 )
}
meder
A: 
var allObjects [] = new Array();
function loopObject() {
    ...
    allObjects.push(this);
}

Then one can loop through all elements of allObjects as necessary using allObjects.length.

faraz.yashar
This is exactly what I answered, except with `allObjects` as a global.
SLaks