The eval function executes a JavaScript code string in the current scope.
Disguised eval
Security Questions
Conclusion
The eval function executes a JavaScript code string in the current scope.
var foo = 1;function test() { var foo = 2; eval('foo = 3'); return foo;}test(); // 3foo; // 1
However, eval is executed in the current scope only when it is called directly and the called function is eval itself.
var foo = 1;function test() { var foo = 2; var bar = eval; bar('foo = 3'); return foo;}test(); // 2foo; // 3
Note: The above code is equivalent to calling eval in the global scope. It works the same as the following two statements:
// Statement 1: directly call the foo variable var foo = 1 under the global scope; function test () {var foo = 2; window. foo = 3; return foo;} test (); // 2foo; // 3 // Method 2: Use the call function to modify the eval execution context to the global scope var foo = 1; function test () {var foo = 2; eval. call (window, 'foo = 3'); return foo;} test (); // 2foo; // 3
In any case, we should avoid using the eval function. 99.9% eval is not used in all scenarios.
Disguised eval
Both the timer functions setTimeout and setInterval can accept strings as their first parameters. This string is always executed in the global scope, so eval is not directly called in this case.
Security Questions
Eval also has security issues because it executes any code that is passed to it. When the code string is unknown or comes from an untrusted source, do not use the eval function.
Conclusion
Do not use eval. Any code that uses it will be questioned in terms of its working method, performance, and security. In some cases, if eval must be used for normal operation, its design will be questioned first. This should not be the preferred solution, A better solution that does not use eval should be fully considered and prioritized.
The above is the JavaScript advanced series-why not use eval content. For more information, see PHP Chinese website (www.php1.cn )!