JavaScript: Call a string as a function with arguments

0 Comments

Man, I sure had trouble giving a proper name to this post.

1.// Convert string to a function reference
2.var strFun = "myFunctionName";
3.var func = eval(strFun);
4. 
5.if (typeof func == 'function') {
6.  // call it
7.  func(param1, param2);
8.}

The string "strFun" is converted to a function "func". If func() checks out to be a valid function using typeof to check if the function exists, then we just call it with the arguments it needs.

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog