When looking at other Daniel's blog, always prompt not to use eval, has not been in-depth study why, always thought is a security problem, also did not study eval of other considerations,
When I recently looked at the "JavaScript Secret Garden" blog, I encountered this problem, and made some summary.
First, the function of the Eval function is to execute a JavaScript code string in the current scope, as in code Snippet 1:
Code Snippet 1
var foo = 1; function Test () { var foo = 2; Eval (' foo = 3 '); return // 3// 1
But eval
only when being called directly and calling the function eval
itself , is executed in the current scope, how to understand this sentence, the above code is the red background part of the description,
The following code Snippet 2 does not belong to the direct call to eval, code Snippet 2 is as follows:
// Code Snippet 2 var foo = 1; function Test () { var foo = 2; var bar = eval; Bar (' foo = 3 '); return // 2// 3
The above code is equivalent to being called in the global scope eval
, as in the following two ways (code snippet 3):
//Code Snippet 3//One: Call the Foo variable directly under the global scopevarFoo = 1;functionTest () {varFoo = 2; Window.foo= 3; returnfoo;} Test (); //2Foo//3 //syntax Two: Use the call function to modify the context of eval execution to a global scopevarFoo = 1;functionTest () {varFoo = 2; Eval.call (window,' foo = 3 '); returnfoo;} Test (); //2Foo//3
In any case , we should avoid the use of eval
functions. 99.9% eval
The scenarios used have solutions that are not used eval
.
Disguised as
eval
setTimeout
both the timer function and setInterval
both can accept the string as their first argument. This string is always executed in the global scope, so it is eval
not called directly in this case.
Security issues
eval
There is also a security issue because it executes any code passed to it, and never use a function when the code string is unknown or comes from an untrusted source eval
.
Conclusion
Never use eval
it, and any code that uses it will be challenged in its way of working, performance and security. If some situations must be used to eval
work properly, first its design will be questioned, which should not be the preferred solution, and a better non eval
-use solution should be fully considered and prioritized.
JS in eval () parsing and why don't use eval