Robbie Fikes Robbie Fikes - 1 month ago 6
Javascript Question

How do you use a for loop to call all functions inside all methods inside an object?

I have a timer called 'updater' that runs every second. I also have an object 'particleFunctions' that contains several functions in its methods. I want all 'update' functions in 'particleFunctions' to execute ever second.

Ideally I want the console.log to output output this message every second:

0
1
2




var updater = setInterval(createParticles, 1000);

var particleFunctions = {
particle0 : function(i){
this.update = function(i){
console.log(i);
}
},
particle1 : function(i){
this.update = function(i){
console.log(i);
}
},
particle2 : function(i){
this.update = function(i){
console.log(i);
}
}
}

function createParticles(){
for (var i = 0; i < Object.keys(particleFunctions).length; i++){
particleFunctions['particle' + i].update(i);
}
}




Answer

Not sure where you want the i to be called, but something like this would do the trick:

var particleFunctions = {
        particle0 : function(i){
            this.update = function(){
                console.log(i);
            }
            return this;
        },
        particle1 : function(i){
            this.update = function(){
                console.log(i);
            }
            return this;
        },
        particle2 : function(i){
            this.update = function(){
                console.log(i);
            }
            return this;
        }
    }
    
    function createParticles(){
        for (var i = 0; i < Object.keys(particleFunctions).length - 1; i++){
            particleFunctions['particle' + i](i).update();
        }
    }
    
    var updater = setInterval(createParticles, 1000);

The main problem is that particleFunctions['particle' + i] returns a function, so you have to call it to be able to call update in sequence.

Also, your Object.keys(particleFunctions).length was giving an index out of bounds so I added the - 1 for the check

Comments