Eval in Javascript

Source: Internet
Author: User

Eval in Javascript

 

 

First, let's give a simple understanding.

Eval can execute the string generation Statement, which is similar to SQL exec.

What is the use of eval? Sometimes we don't know what statements to execute in advance, and we only know what statements to execute when conditions and parameters are given. Eval will be used in this case. For example:

We need to make a function (). The function is to enter the names of two objects on the webpage, and then the program connects the values of these two objects and outputs them.
Function output (A, B)
{
VaR tmpa, tmpb;
Tmpa = Document. all. A. value;
Tmpb = Document. All. B. value;
Document. Write (tmpa + tmpb );
}
Output ('input1', 'input2 ');

In this way, you will be prompted with the error "document. all. A is not an object" and "document. All. B is not an object ". Originally, JavaScript regards A and B as object names. How can JavaScript use the values in a as object names? Now we need to use eval and change the code to this:
Function output (A, B)
{
VaR tmpa, tmpb;
Tmpa = eval ("document. All." + A + ". Value ");
Tmpb = eval ("document. All." + B + ". Value ");
Document. Write (tmpa + tmpb );
}
Output ('input1', 'input2 ');
In this way, JavaScript will first extract the values of A and B, and then run them in combination with the previous document. All and later. value, so you can
The values of input1 and input2 are retrieved successfully.

 

After reading the above, I basically understood what eval means.

Then let's take a look at the following

A little advance, using Dom to replace Images

How to Use eval functions in JavaScript?

 

[Eval () function]

Source: http://blog.csdn.net/ianc/archive/2006/05/29/761094.aspx

Javascript has many tips to make programming easier.
One of them is the eval () function, which can execute a string as a javascript expression.
For example:

VaR the_unevaled_answer = "2 + 3 ";
VaR the_evaled_answer = eval ("2 + 3 ");
Alert ("the un-evaled answer is" + the_unevaled_answer + "and the evaled answer is" + the_evaled_answer );

If you run this eval program, you will see that the string "2 + 3" in Javascript is actually executed.
So when you set the_evaled_answer to eval ("2 + 3"), JavaScript will understand and return the sum of 2 and 3 to the_evaled_answer.
This seems a bit silly, but it can actually make interesting things. For example, you can use eval to directly create a function based on user input.
This allows the program to change the program itself based on time or user input. You can achieve amazing results by taking the opposite picture.
In practice, Eval is rarely used, but you may have seen people use eval to obtain objects that are hard to index.

One of the problems with the Document Object Model (DOM) is that sometimes it is a pain to get the object you want.
For example, here is a function that asks the user which image to transform: You can use the following function to change which image:

Function swapone ()
{
VaR the_image = prompt ("Change parrot or cheese ","");
VaR the_image_object;

If (the_image = "parrot ")
{
The_image_object = Your role Doc ument. Parrot;
}
Else
{
The_image_object = plain Doc ument. Cheese;
}

The_image_object.src = "ant.gif ";
}

Together with these image tags:

[Img src = "/stuff3a/parrot.gif" name = "parrot"]
[Img src = "/stuff3a/cheese.gif" name = "Cheese"]

Note the following statements:

The_image_object = Your role Doc ument. Parrot;

It applies an image object to a variable. Although it looks a bit strange, it has no Syntax problems.
But what if you have 100 images instead of two images? You have to write a lot of if-then-else statements. If it works like this:

Function swaptwo ()
{
VaR the_image = prompt ("Change parrot or cheese ","");
Required parameter Doc ument. the_image.src = "ant.gif ";
}

Unfortunately, JavaScript will look for images named the_image instead of the desired "Cheese" or "parrot,
So you get the error message: "I have never heard of an object named the_image ".

Fortunately, Eval can help you get the object you want.

Function simpleswap ()
{
VaR the_image = prompt ("Change parrot or cheese ","");
VaR the_image_name = "zookeeper Doc ument." + the_image;
VaR the_image_object = eval (the_image_name );
The_image_object.src = "ant.gif ";
}

If you enter "parrot" in the prompt box, create an example string in the second line, that is, the example Doc ument. Parrot. contains the third part of eval.
The line means: "Give me the object named Doc ument. parrot"-that is, the image object you want. Once you obtain this image object, you can
Maybe srcflood is set to ant.gif. A little scared? No. In fact, this is quite useful and is often used by people.

We often go to the eval function in the middle of JavaScript,
Some people think this function is very strange. It can make some strings very powerful.
This function is used when we need to convert a common string into a specific object.

The eval function evaluates a string used as a numeric expression. Its syntax is:

Eval (expr)

Expr is a string parameter evaluated. If the string is an expression, Eval evaluates the value of this expression. If this parameter represents one or more JavaScript statements, Eval executes these statements. The eval function can be used to convert a date from a format (always string) to a numeric expression or number.

====================================
Eval function
Function: first explain the JavaScript code and then execute it.
Usage: eval (codestring)
Codestring is a string containing JavaScript statements. It is compiled using the JavaScript engine after eval.

Note:

Example: eval (ID + "_ icon. src ="/IMGs/collapse_up.gif '");
ID is a previously set parameter, while the string in double quotation marks needs to be compiled.

Reference:
--------------------------------------------------------------------------------
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 the head '");
Head. style. Display = "Block"
}
Else
{
Top. topframeset. rows = "31 ,*";
Eval (ID + "_ icon. src ="/IMGs/collapse_down.gif '");
Eval (ID + "_ icon. Alt = 'expand the head '");
Head. style. Display = "NONE"
}
}

If you still do not understand the eval functions in Javascript

Source: http://www.x2blog.cn/supnate/#sid.1735/page.1/

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]

 

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.

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.