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 PeterM for How to execute a JavaScript function when I have its name as a string

$
0
0

There are several executeByName functions here which works fine, unless name contains square brackets - issue I ran into - as I have dynamically generated names. So above functions will fail on names like

app.widget['872LfCHc']['toggleFolders']

As a remedy, I've made function to take this into account too, maybe someone will find it usefull:

Generated from CoffeeScript:

var executeByName = function(name, context) {  var args, func, i, j, k, len, len1, n, normalizedName, ns;  if (context == null) {    context = window;  }  args = Array.prototype.slice.call(arguments, 2);  normalizedName = name.replace(/[\]'"]/g, '').replace(/\[/g, '.');  ns = normalizedName.split(".");  func = context;  for (i = j = 0, len = ns.length; j < len; i = ++j) {    n = ns[i];    func = func[n];  }  ns.pop();  for (i = k = 0, len1 = ns.length; k < len1; i = ++k) {    n = ns[i];    context = context[n];  }  if (typeof func !== 'function') {    throw new TypeError('Cannot execute function '+ name);  }  return func.apply(context, args);}

For better readability check also CoffeeScript version:

executeByName = (name, context = window) ->    args = Array.prototype.slice.call(arguments, 2)    normalizedName = name.replace(/[\]'"]/g, '').replace(/\[/g, '.')    ns = normalizedName.split "."    func = context    for n, i in ns        func = func[n]    ns.pop()    for n, i in ns        context = context[n];    if typeof func != 'function'        throw new TypeError 'Cannot execute function '+ name    func.apply(context, args)

Viewing all articles
Browse latest Browse all 38

Trending Articles



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