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");