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?
views:
74answers:
3
+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
2010-07-13 20:05:53
Why was this downvoted?
SLaks
2010-07-13 20:27:42
Wouldn't reading the all array from the bottom and removing each item after use kill the instance and save memory?
faraz.yashar
2010-07-13 20:35:47
@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
2010-07-13 20:38:24
@SLaks: Thanks a lot.
faraz.yashar
2010-07-13 20:46:26
TypeError: Cannot call method 'push' of undefined on the line `LoopObject.all.push(this);`
faraz.yashar
2010-07-13 21:46:24
@faraz: You forgot `LoopObject.all = [];` (Or you deleted or re-assigned it elsewhere)
SLaks
2010-07-13 21:54:15
The empty square brackets causes a token error: "Uncaught SyntaxError: Unexpected token ]"
faraz.yashar
2010-07-13 22:03:10
@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
2010-07-13 22:34:45
+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
2010-07-13 20:06:42
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
2010-07-14 00:10:14