The JS eval function

1.eval () function operates: accept a string str as a parameter, and this parameter as the script code to execute.

2. The parameters are:
(1) if the parameter is an expression, eval () function to execute the expression;
(2) if the parameter is a Javascript statements, eval () statement will be executed Javascript

3. Note:
(If the execution result is returned to a value not return undefined, if the parameter is not a string, then directly back to the parameter)

4. Syntax: eval (string),

5. Case:

eval ( "var a = 1"); // declare a variable assignment and a 1.

eval ( "2 + 3"); // add operation performed, and returns the computed value.

eval ( "mytest ()"); // execute mytest () function.

eval ( "{b: 2}"); // declare an object. If you want to return this object, the need to nest outside layer of small objects comprising the following: eval ( "({b: 2})");

NOTE: use eval to parse JSON format string when the {} will be parsed into blocks of code, not the literal object
// 1 on the front of the splicing JSON-formatted string.  "Var = O"
// 2. JSON format of the string () enclose, {} will not be parsed into blocks of code, but the expression

6. function scope: eval () function does not create a new scope, and its scope is the scope in which it is sometimes necessary to set the scope eval () function is global, of course you can implement eval () to use in the global field, this can be used when window.eval () way.

7.Function and eval What is the difference?

Common: you can speak string into js code

Different points: Function created out of the function, and does not directly call, only manually when the function to call out when it is created, eval is the string into the code directly executed.

Guess you like

Origin www.cnblogs.com/huhewei/p/12466967.html