When you have to execute a string as code, many people first think of using eval, but in fact, using the new function is more secure.
Why is it safe? Look at an example.
<script> var a = 1; Eval ("Var a=2;"); Change the current domain variable a alert (a); New Function ("Var a=3;") (); Do not change the current scope of the variable alert (a);</script>
eval can affect the current scope and all the variables of the parent scope, and the new function is run within a separate function, and his parent scope is window instead of the current scope. Let's look at another example.
<script> var a = 1; Eval ("Var a=2;"); Change the current domain variable a alert (a); New Function ("Var a=3;") (); Do not change the current scope of the variable alert (a);</script>
one might say that the new function is isolated from the current scope. So how do I get a string as a value after the code runs? For example, a classic application that transforms a JSON string into an object literal
such as var B = ' {' A ': ' B '} ' You can add a return directly, such as var C = new Function ("Return" +b) (); So C is an object of the same format.
This article is from the "Leeturn" blog, make sure to keep this source http://9476439.blog.51cto.com/9466439/1567361
The difference between the eval of JavaScript and the new function