JavaScript eval () usage analysis

Source: Internet
Author: User
Tags eval function definition object object javascript eval

Definitions and usage
The eval () function computes a string and executes the JavaScript code in it.

Grammar
eval (string) parameter description
String required. The string to evaluate, which contains the JAVASCRIPT expression to evaluate or the statement to execute.

return value
The value, if any, obtained by calculating the string.

Description
The method accepts only the original string as a parameter, and if the string argument is not the original string, the method returns without any changes. Therefore, do not pass a String object as an argument for the eval () function.

If you attempt to overwrite the Eval attribute or assign the eval () method to another property and call it through this property, the ECMAScript implementation allows a Evalerror exception to be thrown.

A special note is that the object declaration syntax "{}" does not return a value, which needs to be enclosed in parentheses to return the value, as the simple example reads:

  code is as follows copy code

var code1= ' "A" + 2 ';   //Expression

    varcode2= ' {a:2} ';     //statement

    Alert (eval (code1));    //-> ' A2 '

    Alert (eval (code2));    //->undefined

    Alert (eval (' + Code2 + '));   //->[object Object]

As you can see, for an object declaration statement, it is simply execution and cannot return a value. In order to return an object declaration statement such as the usual "{}", you must enclose it in parentheses to convert it to an expression to return its value. This is one of the fundamentals of using JSON for AJAX development. As you can see clearly in the example, the second alert statement outputs the undefined, and the third with parentheses is the object that the statement represents.
Now the focus of this article is how to execute global code within a function. To illustrate this issue, let's look at an example:

The code is as follows Copy Code

var s= ' global '; Define a global variable

function Demo1 () {

Eval (' var s= ' local ');

}

Demo1 ();

alert (s); ->global

Well understood, the DEMO1 function above is equivalent to: function Demo1 () {var s= ' local ';}, which defines a localized variable s.
So the final output is global is not a strange thing, after all, we can clearly distinguish between local and global variables.
With a closer look, you can see that the eval function is always executed within the context variable space (also known as: Package, closure) that calls it, whether it is a variable definition or a function definition, so the following code produces an error that is undefined by the function:

The code is as follows Copy Code

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 the local space and can be accessed within the DEMO2 function and is inaccessible outside.

In actual Ajax development, sometimes we need to dynamically get code from the server to execute to mitigate the problem of loading code too much at a time, or some code is generated through JavaScript itself and wants to be executed using the Eval function.
However, this dynamic acquisition code is generally done within the function, such as:

The code is as follows Copy Code

function Loadcode () {

Varcode=getcode ();

eval (code);

}

It can be seen that eval is impossible to execute in the global space, which brings a lot of problems to development, but also see a lot of people for this depressed.
But now I finally found a solution, hey, can be compatible with IE and Firefox, the following methods:

The code is as follows Copy Code

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 within a function, you can invoke the X2.eval_r (code) method by invoking the following example:

The code is as follows Copy Code

var s= ' global ';

function Demo3 () {

X2. Eval (' var s= ' local ');

}

Demo3 ();

alert (s); -> ' Local '

Visible, the global variable s= "local" is redefined within the DEMO3 function.
Note that X2.eval does not return a value, and if you want to evaluate the expression, use the system's eval function. X2. Eval is designed to do only global code definitions.

Instance

Example 1
In this case, we'll use Eval () on several strings, and look at the returned results:

The code is as follows Copy Code

<script type= "Text/javascript" >

Eval ("X=10;y=20;document.write (x*y)")

document.write (eval ("2+2"))

var x=10
document.write (eval (x+17))

</script> output:

200
4
27


The ID is the previously set parameter, and the string in double quotes is the one that needs to be compiled

Example: eval (id + "_icon.src="/imgs/collapse_up.gif ' ");


Reference:
--------------------------------------------------------------------------------

The code is as follows Copy Code
function tophide (ID)//id indicates menu
{
if (top.topframeset.rows = = "31,*")
{
Top.topframeset.rows = "86,*";
Eval (id + "_icon.src="/imgs/collapse_up.gif ');
Eval (id + "_icon.alt= ' Collapse");
Head.style.display = "Block"
}
Else
{
Top.topframeset.rows = "31,*";
Eval (id + "_icon.src="/imgs/collapse_down.gif ');
Eval (id + "_icon.alt= ' Expand");
Head.style.display = "None"
}
}
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.