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

$
0
0
  const myFnCollection = {    myFnStringName: function(args) {}  };  let fn = 'myFnStringName';  // 1. Recommended  if (typeof window[fn] === 'function') {    window[fn](args);  }  // 2. Recommended  if (typeof myFnCollection[fn] === 'function') {    myFnCollection[fn](args);  }  // 3. Eval is evil ;)  if (typeof eval(fn) === 'function') {    eval(fn)(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>