Jason Basanese Jason Basanese - 1 year ago 64
Javascript Question

How to make a function that calls an object method on every object in a list?

I want to be able to invoke a given method name on all objects in a given list. Say the method I want to call is jump, and I have a list of people who have varying jump methods. Some jump at different angles, others higher or lower etc etc. But I want to call the jump method on all of my list of basketball players in order to see who gets to be on the team.

function doMethodToList(list, method){
for(var i = 0; i< list.length; i++){
var roster = [new Jack(), new Jill(), new Brody()];
doMethodToList(roster, "jump");

I am thinking something like the above code should work. However it would throw an error when calling
doMethodToList(roster, "jump")
because I am trying to use a string as a method. Any ideas how to make this function work? Maybe am I thinking of this all wrong? Answers highly appreciated.

Answer Source

You can simply do the following in your loop:

if (list[i][method]) list[i][method]();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download