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

Ankur Bawiskar
Tera Patron
Tera Patron

Hi,

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 
}

Regards
Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

Hi Ankur,

Thanks for your response but that did not work.

Hi,

can you check if this at least calls the function

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

Regards
Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

Hi,

It does not even call the function, no.