Loop through All Objects of a Class
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 t开发者_如何学Pythonhere a way to place each new object into an array upon initialization?
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.
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 )
}
var allObjects [] = new Array();
function loopObject() {
...
allObjects.push(this);
}
Then one can loop through all elements of allObjects
as necessary using allObjects.length
.
精彩评论