Since eval()
is evil, and new Function()
is not the most efficient way to achieve this, here is a quick JS function that returns the function from its name in string.
- Works for namespace'd functions
- Fallbacks to null-function in case of null/undefined string
- Fallbacks to null-function if function not found
function convertStringtoFunction(functionName){ var nullFunc = function(){}; // Fallback Null-Function var ret = window; // Top level namespace // If null/undefined string, then return a Null-Function if(functionName==null) return nullFunc; // Convert string to function name functionName.split('.').forEach(function(key){ ret = ret[key]; }); // If function name is not available, then return a Null-Function else the actual function return (ret==null ? nullFunc : ret); }
Usage:
convertStringtoFunction("level1.midLevel.myFunction")(arg1, arg2, ...);