Quantcast
Channel: How to execute a JavaScript function when I have its name as a string - Stack Overflow
Viewing all articles
Browse latest Browse all 38

Answer by SJ00 for How to execute a JavaScript function when I have its name as a string

$
0
0

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, ...);

Viewing all articles
Browse latest Browse all 38

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>