1, the Eval method can only be used in the non-strict mode, in use strict is not allowed this method.
2. The eval function receives a parameter s, and if S is not a string, it returns s directly. Otherwise, the S statement is executed. If the S statement execution result is a value, this value is returned, otherwise undefined is returned. It is important to note that the object declaration syntax "{}" does not return a value and needs to be enclosed in parentheses to return a value. As follows:
var code1= ' "A" + 2 '; An expression
var code2= ' {a:2} '; Statement
Alert (eval (code1)); ' A2 '
Alert (eval (code2)); ->2
Alert (eval (' (' + Code2 + ') '); ->[object Object]
When an object is inside a string in eval, parentheses can return the original object as it is, and if Code2={a:2,b:3} is directly eval (code2), the parentheses will return the Code2 as is.
3. Eval is used directly inside the function and returns a local variable
function Te () {
Eval (' var a=1; ')
}
Te ();
alert (a);//This will cause an error because a is a local variable and can only be used within the Te method
4. There are two ways to make the eval used inside the function a global variable
(1) using Window.eval () to make it a global
function Te () {
Window.eval (' var a=1 ')
}
Te ();
The A variable is also global
(2) function te () {
var a=eval;
A (' var b=1 ');
}
Te ();
In this way, variable B is also global.
So in the non-strict mode, there is one more way to convert the JSON string form into the form of an object. is to use Var m=eval (' (' +data+ ') '), M is a JSON object. The function and Json.parse () are similar, but when the JSON that has been converted to an object through Json.parse () is no longer called by the function to continue the conversion, this will cause an error, but the eval () method will not be used when the incoming string is an object to continue using the above method. The original object is returned.
The use of the Eval () method in JS and some special ways to use it