Javascript call function by name string

Javascript Feb 05, 2020 Viewed 257 Comments 0

Sometimes it is necessary to call functions dynamically. Use the string of the function name to execute the function. Here are two methods.

Using eval function

The eval method is to interpret and execute the script at runtime. Eval is usually used in some scenarios that require dynamic execution of strings or conversion of strings to javascript objects, such as converting json strings to javascript objects.

eval() method raises several issues:

Security: your string can be injected with other commands by third-party scripts or user input.

Debugging: it’s difficult to debug errors — you have no line numbers or obvious points of failure.

Optimization: the JavaScript interpreter cannot necessarily pre-compile the code because it could change. While interpreters have become increasingly efficient, it’ll almost certainly run slower than native code.

Unfortunately, eval is very powerful and it’s easy for less experienced developers to overuse the command.

Don't use eval unless you have no choice.

function testFunc(str) {
    console.log(str);
}

var funcName = "testFunc";
var params = "hello world! eval";
var funcCall = funcName + "('" + params + "');";
var ret = eval(funcCall);

Try it Yourself »

Using window variable

You can use eval() method to invoke a JavaScript function whose name is stored in a string variable but there’s a better method that doesn’t require eval.

In fact, the method definitions are all extensions to the window variable. We often see these situations when debugging in F12.

// Define a method
function testFunc(str) {
    console.log(str);
}
// Call the method
var funcName = "testFunc";
var params = "hello world! window";
if (window[funcName] != null && typeof window[funcName] === "function") {
    window[funcName](params);
}

Try it Yourself »

Updated Feb 05, 2020