In JavaScript, eval
is not a good idea! The eval
page of MDN states: > Obsolete This feature is obsolete. Although the browser still supports it, it is not recommended in new projects. Try to avoid using it.
eval
Execute a string containing the code, for example:
eval("var x = 'Hello from eval!';"); console.log(x);
eval
Some problems will arise:
Unfortunately, eval
is very powerful and inexperienced developers can easily overuse this command. Despite the warning, eval
still works – even in strict mode – but you can usually avoid it. In the past, it was mainly used to deserialize JSON strings, but we now have a safer JSON.parse
method. However, if we have a function name in a string, for example:
// 我们要运行的函数 var fnstring = "runMe"; function runMe() { // 执行操作 }
How do we execute eval
functions without using runMe()
? I've recently encountered this while using the HTML5 History API; the pushState
method does not allow you to store direct references to a function, so you need to define its name as a string. You may face similar challenges when using Web Workers or any other API that serializes objects.
The easiest and safest implementation solution without eval
is a series of conditions, such as:
// 我们要运行的函数 var fnstring = "runMe"; switch (fnstring) { case "functionX": functionX(); break; case "functionY": functionY(); break; case "functionZ": functionZ(); break; case "runMe": runMe(); break; }
It's safe, but it's quite inefficient and headache to write if you want to call dozens of functions. A better solution is to use the window
object, which references the current window and all items in it. We can check if fnstring
is available as an object in window
and if it is a function, run it, for example:
// 我们要运行的函数 var fnstring = "runMe"; // 查找对象 var fn = window[fnstring]; // 对象是否为函数? if (typeof fn === "function") fn();
If necessary, you can perform additional checks to ensure that the function has the expected name. What if the function we are calling has parameters - maybe stored in an array? No problem; we just need to use apply
Method:
// 函数名称和要传递的参数 var fnstring = "runMe"; var fnparams = [1, 2, 3]; // 查找对象 var fn = window[fnstring]; // 对象是否为函数? if (typeof fn === "function") fn.apply(null, fnparams);
So this is another reason to stop using eval
. Additionally, this solution is safer, has fewer errors, is easier to debug, and is often faster to execute. Hope it helps you.
eval
eval()
? The eval()
function in JavaScript is a powerful tool that allows you to execute arbitrary code strings. However, using eval()
is often considered a bad practice due to security and performance issues. It can make your code vulnerable to injection attacks. Additionally, modern JavaScript engines optimize the performance of code, but they cannot optimize code executed by eval()
. Therefore, it is very beneficial to know how to call JavaScript functions with strings without using eval()
. This can be achieved by using window
objects or Function
constructors, which are safer and more efficient alternatives.
window
objects to call JavaScript functions using strings? The window
object in JavaScript represents the window displayed by the browser. It is a global object in the browser environment, and all global variables and functions become attributes and methods of window
objects. You can use the window
object to call the function using a string by accessing the function as a property of the window
object. Here is an example:
eval("var x = 'Hello from eval!';"); console.log(x);
In this code, "hello" is a property of the window
object, which refers to the hello()
function. Therefore, window["hello"]
calls the hello()
function.
Function
constructor, how do you use it to call a function using a string? The Function
constructor in JavaScript creates a new Function
object. This is a less common but still effective way to define a function. You can use the Function
constructor to call the function using a string by passing the string to the constructor. Here is an example:
// 我们要运行的函数 var fnstring = "runMe"; function runMe() { // 执行操作 }
In this code, the Function
constructor creates a new function that takes two arguments "a" and "b" and returns their sum. Parameters and function bodies are passed as strings.
Yes, you can call functions using strings even if the function is some method of an object. You can do this by accessing the object's properties, which is similar to how you handle window
objects. Here is an example:
// 我们要运行的函数 var fnstring = "runMe"; switch (fnstring) { case "functionX": functionX(); break; case "functionY": functionY(); break; case "functionZ": functionZ(); break; case "runMe": runMe(); break; }
In this code, "hello" is a property of the obj
object, which references the hello()
method. Therefore, obj["hello"]
calls the hello()
method.
While it may be useful in some cases to call JavaScript functions using strings, it also has some limitations. One limitation is that it only applies to a method of a global function or known object. If the function is not a property of a known object, it cannot be called with a string. Another limitation is that you cannot pass parameters directly to the function. If the function accepts parameters, you need to include them in a string, or use other functions to pass them. Despite these limitations, calling functions with strings is still a powerful tool when used correctly.
The above is the detailed content of How to Call a JavaScript Function From a String Without Using eval. For more information, please follow other related articles on the PHP Chinese website!