开发者

Loop through All Objects of a Class

开发者 https://www.devze.com 2023-01-06 20:40 出处:网络
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 fun

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消