Jason Basanese
Jason Basanese

Reputation: 710

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++){
      list[i].method();
   }
} 
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.

Upvotes: 1

Views: 61

Answers (2)

Abderraouf El Gasser
Abderraouf El Gasser

Reputation: 136

You can simply do the following in your loop:

if (list[i][method]) list[i][method]();

Upvotes: 4

Musa
Musa

Reputation: 97672

To access a property of an object with a string you use square bracket notation

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

Upvotes: 4

Related Questions