Construct one object to save all functions with their names, then call like list[name]()
.
eval() (like eval('the name of your function')
) may be another solution, but it will be dangerous and may be slower.
Like MDN said:
eval() is a dangerous function, which executes the code it's passed
with the privileges of the caller. If you run eval() with a string
that could be affected by a malicious party, you may end up running
malicious code on the user's machine with the permissions of your
webpage / extension. More importantly, a third-party code can see the
scope in which eval() was invoked, which can lead to possible attacks
in ways to which the similar Function is not susceptible.
eval() is also slower than the alternatives, since it has to invoke
the JS interpreter, while many other constructs are optimized by
modern JS engines.
var functionList = {'a':function(){console.log('a')}, 'b':function(){console.log('b')}}
function main (str) {
functionList[str]()
}
main('a')
main('b')