JavaScript: Call a string as a function with arguments

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

// Convert string to a function reference
var strFun = "myFunctionName";
var func = eval(strFun);

if (typeof func == 'function') {
// call it
func(param1, param2);

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