How can I convert a string into a function call?

Keith Morgan
Kilo Explorer

I have a process where I iterate through a loop and set a string as a value from each iteration. The string value will be the name of a function in the same Script Include that I then want to call (and pass variables to as parameters).

For example;

  • If the 'strFunctionName' value is 'myFunction1' I want a way to call myFunction1(var1, var2)
  • if the 'strFunctionName' value is 'myFunction2' I want a way to call myFunction2(var1, var2)

These functions 'myFunction1(var1, var2)' and 'myFunction2(var1, var2)' will already exist, and the variables that will be passed will be the same no matter the function, I just need a way of dynamically calling them from a string.

for (var loop = 0; loop < exampleListOfFunctions.length; loop++;){
     var strFunctionName = exampleListOfFunctions[loop];
     this.<<strFunctionName>>(var1, var2); // it is this function call that I need to be able to do 
}

 

I expect there to be a number of functions that will need to be called so using a Switch or If statement isn't appropriate due to having to manage it all.

Early investigations have led me down the path of both Eval() and GlideEvaluator but I have not been able to get either method to work.

Has anyone got any ideas?

1 ACCEPTED SOLUTION

Mahendra RC
Mega Sage

Hello @Keith Morgan 

Could you please check once with below code:

try thisfor (var loop = 0; loop < exampleListOfFunctions.length; loop++){
     var strFunctionName = exampleListOfFunctions[loop];
     this[strFunctionName](var1, var2); // it is this function call that I need to be able to do 
}

Please mark my respsone as helpful/correct, if it answer your question.

Thanks

View solution in original post

6 REPLIES 6

Mahendra RC
Mega Sage

Hello @Keith Morgan 

Could you please check once with below code:

try thisfor (var loop = 0; loop < exampleListOfFunctions.length; loop++){
     var strFunctionName = exampleListOfFunctions[loop];
     this[strFunctionName](var1, var2); // it is this function call that I need to be able to do 
}

Please mark my respsone as helpful/correct, if it answer your question.

Thanks

Hi Mahendra,

Thank you very much. That works exactly as I wanted. Great stuff 🙂