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

$
0
0

Here's a bit robust and reusable solution I ended up implementing for one of my projects.

A FunctionExecutor Constructor Function

Usage:

let executor = new FunctionExecutor();executor.addFunction(two)executor.addFunction(three)executor.execute("one");executor.execute("three");

Obviously in the project the adding of all the functions that required to be called by name was done by a loop.

The function Executor:

function FunctionExecutor() {  this.functions = {};  this.addFunction = function (fn) {    let fnName = fn.name;    this.functions[fnName] = fn;  }  this.execute = function execute(fnName, ...args) {    if (fnName in this.functions && typeof this.functions[fnName] === "function") {      return this.functions[fnName](...args);    }    else {      console.log("could not find " + fnName +" function");    }  }  this.logFunctions = function () {    console.log(this.functions);  }}

Example Usage:

function two() {  console.log("two"); }function three() {  console.log("three");}let executor = new FunctionExecutor();executor.addFunction(two)executor.addFunction(three)executor.execute("one");executor.execute("three");

Viewing all articles
Browse latest Browse all 38

Trending Articles



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