Many people think that the eval () method is evil (evil). This method can be used to execute arbitrary strings as JavaScript code. We should not use the Eval () method as much as possible. For example, you can use square brackets to get the value of an object property:
Antipatternvar property = "Name", Alert (eval ("obj." + property);//Preferredvar property = "name"; alert (Obj[property) );
In addition, JavaScript's setinterval () and settimeout () methods have similar problems. You should also avoid passing strings as arguments to these methods:
Antipatternssettimeout ("MyFunc ()"), SetTimeout ("MyFunc (1, 2, 3)", +//Preferredsettimeout (MyFunc, 1000); SetTimeout (function () { myFunc (1, 2, 3);}, 1000);
The new function () can also accept the string as a parameter, but this should also be avoided. The difference between new function () and eval () is that the variables in the code executed by eval () will "become" global variables, but new function () is not.
Console.log (typeof un); "Undefined" console.log (typeof deux); "Undefined" console.log (typeof trois); "Undefined" var jsstring = "var un = 1; Console.log (un); "; eval (jsstring); Logs "1" jsstring = "var deux = 2; Console.log (deux); "; New Function (jsstring) (); Logs "2" jsstring = "var trois = 3; Console.log (trois); ";( function () { eval (jsstring);} ()); Logs "3" Console.log (typeof un); "Number" Console.log (typeof deux); "Undefined" console.log (typeof trois); "Undefined"
In addition, the string code in eval () can access global variables in the program, while the new function does not. It is important to note that the function and new function effects are identical:
(function () { var local = 1; Eval ("local = 3; Console.log (local) "); Logs 3 console.log (local);//Logs 3} ());(function () { var local = 1; Function ("Console.log (typeof local);") (); Logs undefined} ());
JavaScript Basics Avoid using eval () (006)