Eval function usage

Source: Internet
Author: User

Two purposes of this article:
(1) Introduce eval function usage in Javascript
(2) how to execute global functionsCode

►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:

    1. VaR code1 = '"A" + 2'; // expression
    2. VaR code2 = '{A: 2}'; // statement
    3. Alert (eval (code1); //-> 'a2'
    4. Alert (eval (code2); //-> undefined
    5. Alert (eval ('+ code2 +'); //-> [object]

Copy code

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:

    1. VaR S = 'global'; // defines a global variable.
    2. Function demo1 (){
    3. Eval ('var S = "local "');
    4. }
    5. Demo1 ();
    6. Alert (s); //-> global

Copy code

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:

    1. VaR S = 'function test () {return 1 ;}'; // a Function Definition Statement
    2. Function demo2 (){
    3. Eval (s );
    4. }
    5. Demo2 ();
    6. Alert (test (); //-> error: test is not defined

Copy code

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:

    1. Function loadcode (){
    2. VaR code = getcode ();
    3. Eval (CODE );
    4. }

Copy 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:

    1. VaR X2 ={} // my namespace :)
    2. X2.eval = function (CODE ){
    3. If (!! (Window. attachevent &&! Window. Opera )){
    4. // IE
    5. ExecScript (CODE );
    6. } Else {
    7. // Not IE
    8. Window. eval (CODE );
    9. }
    10. }

Copy 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:

    1. VaR S = 'global ';
    2. Function demo3 (){
    3. X2.eval ('var S = "local "');
    4. }
    5. Demo3 ();
    6. Alert (s); //-> 'local'

Copy code

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.


it 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 correct or not. If you know the solution,

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.