Deep understanding of eval functions in javascript

Source: Internet
Author: User
A deep understanding of eval functions in javascript source: Terry's column found that it is not so easy to give a proper title for this article, so I would like to explain the following two purposes: (1) this article introduces the eval function usage in javascript (2) how to execute global code in the function & #9658; first, let's talk about eval usage SyntaxHig

Deep understanding of eval functions in javascript
Source: Terry's column


It is not that easy to start a proper title for this article, so I would like to explain the following two purposes:
(1) Introduce eval function usage in javascript
(2) how to execute global code in the function

►First, let's talk about eval usage. The content is relatively simple and you can skip it if you are familiar with it.
The eval function receives a parameter s. If s is not a string, s is directly returned. Otherwise, execute the s statement. If the execution result of the s statement is a value, this value is returned; otherwise, undefined is returned.
Note that the object declaration Syntax "{}" does not return a value and must be enclosed in parentheses to return the value. A simple example is as follows:

Var code1 = "a" + 2; // expression
Var code2 = {a: 2}; // statement
Alert (eval (code1); //-> a2
Alert (eval (code2); //-> undefined
Alert (eval (+ code2 +); //-> [object Object]
As you can see, for object declaration statements, they are only executed and cannot return values. To return a commonly used object declaration statement such as "{}", it must be enclosed in parentheses to convert it into an expression before returning its value. This is also one of the basic principles of Ajax development using JSON. In the example, we can clearly see that the second alert statement outputs undefined, and the third statement outputs the object represented by the statement after parentheses.

►The focus of this Article is on how to execute global code in the function. To illustrate this problem, let's first look at an example:

Var s = global; // defines a global variable.
Function demo1 (){
Eval (var s = "local ");
}
Demo1 ();
Alert (s); //-> global
Well understood, the above demo1 function is equivalent to: function demo1 () {var s = local ;}, which defines a local variable s.
So the final output is global. After all, everyone can clearly distinguish between local variables and global variables.
After careful consideration, we can find that the eval function is always executed in the context variable space (also called package, closure) that calls it, both the variable definition and the function definition are the same, so the following code will generate an undefined function error:

Var s = function test () {return 1 ;}; // a function Definition Statement
Function demo2 (){
Eval (s );
}
Demo2 ();
Alert (test (); //-> error: test is not defined
This is because the test function is defined in a local space and can be accessed in the demo2 function.

In actual Ajax development, sometimes we need to dynamically obtain code from the server for execution to reduce the problem of loading too much code at a time, or some code is generated by Javascript itself, you want to use the eval function for execution.
However, such dynamic code acquisition is generally completed in the function, for example:

Function loadCode (){
Var code = getCode ();
Eval (code );
}
It can be seen that eval cannot be executed in the global space, which brings many problems to the development, and many people have seen this depressing situation.

But now I finally found a solution. Hey hey, it can be compatible with IE and Firefox at the same time. The method is as follows:

Var X2 ={} // my namespace :)
X2.Eval = function (code ){
If (!! (Window. attachEvent &&! Window. opera )){
// Ie
ExecScript (code );
} Else {
// Not ie
Window. eval (code );
}
}
Now, if you want to define global code in the function, you can call the X2.Eval (code) method. An example is as follows:

Var s = global;
Function demo3 (){
X2.Eval (var s = "local ");
}
Demo3 ();
Alert (s); //-> local
We can see that the global variable s = "local" is redefined in the demo3 function ".
It should be noted that X2.Eval does not return values. If you want to evaluate the expression, you still need to use the eval function of the system. X2.Eval is designed for Global Code definition only.

In fact, some people may feel that the problem is too easy to solve, but they need some luck and skills to find this solution:
(1) For ie browsers, execScript is provided by default to execute code in the global space, but there are not many people who know it.
(2) For Firefox, if the eval function is called directly, the function is executed in the caller's space. If window. eval is called, the function is executed in the global space. It is estimated that there will be fewer people. After all, alert (eval = window. eval) returns true!

The eval function of Firefox is indeed quite strange, but the source can also be found from the javascript specification:

If value of the eval property is used in any way other than a direct call (that is, other than by the explicit use of its
Name as an Identifier which is the MemberExpression in a CallExpression), or if the eval property is assigned,
An EvalError exception may be thrown.
This means that the execution of the eval function is related to the caller, but the execution context is not mentioned. Therefore, it is hard to say whether IE and Firefox are the same. It is good to know the solution.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.