JavaScript eval () function

Source: Internet
Author: User
Tags javascript eval

definition and Usage:the eval () function computes a string and executes the JavaScript code in it.

Syntax:eval (String)

Parameters Description
String Necessary. The string to evaluate that contains the JAVASCRIPT expression to be evaluated or the statement to execute.

return Value: The value, if any, obtained by calculating a string.

Description:

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

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

thrown

Throws an SyntaxError exception if there are no valid expressions and statements in the argument.

If Eval () is called illegally, a Evalerror exception is thrown.

If the Javascript code passed to eval () generates an exception, eval () passes the exception to the caller.

Hints and notes

Tip: Although the function of eval () is very powerful, there are not many cases where it is used in practice.

ExampleExample 1

In this example, we will use Eval () on a few strings and see the results returned:

<script type= "Text/javascript" > eval("X=10;y=20;document.write (x*y)") document.write (eval ( "x=10" ) var  document.write (eval (x+17)) </script>

Output:

200427
Example 2

Take a look at the result of the Eval () return in other cases:

Eval ("2+3")    //  return 5var myeval = eval;    // Evalerror exception Myeval ("2+3") may be thrown ;    // Evalerror exceptions may be thrown

The following code can be used to detect whether the parameters of eval () are legitimate:

Try   {     alert ("Result:" + eval (Prompt ("Enter An expression:", "")));     } Catch (Exception) {     alert (exception);     }
/////////**************************************************************//////////

It is important to note that the object declaration syntax "{}" does not return a value and needs to be enclosed in parentheses to return a value, a simple example is as follows:

var //   //////Alert (eval (' (' + Code2 + ') '); //

As you can see, for an object declaration statement, it is only execution and cannot return a value. In order to return an object declaration statement such as a commonly used "{}", it must be enclosed in parentheses to convert it to an expression in order to return its value. This is one of the basic principles of AJAX development using JSON. As you can see clearly in the example, the second alert statement outputs undefined, and the third one with parentheses outputs the object represented by the statement.
Now the focus of this article is how to execute global code within a function. To illustrate this problem, let's look at an example:

var //  function  demo1 () {eval (' var s= ' local'//


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

var //  function//


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 the actual Ajax development, sometimes we need to get the code from the server dynamically, to alleviate the problem of loading too much code one time, or some code is generated by JavaScript itself, want to use the Eval function to make it execute.
But this kind of dynamic get code work is usually done within the function, such as:


function Loadcode () {     Varcode=getcode ();     


It can be seen that eval cannot be implemented in the global space, which brings a lot of problems to development, but also seen a lot of people depressed.
But now I finally found a solution, hey, can also be compatible with IE and Firefox, the method is as follows:

var //  X2. eval=function(code) {        if(!! (Window.attachevent &&!) Window.opera)) {            //           execScript (code);        } Else {           //          window.eval (code);     
}


Now, if you want to define global code within a function, you can call the X2.eval_r (code) method, an example is as follows:

var s= ' global 'function  Demo3 () {     X2. Eval (' var s= ' local'//


It is visible that the global variable s= "local" is redefined within the DEMO3 function.
It is important to note that X2.eval does not return a value, and if the expression is evaluated, the system's eval function is used. X2. The eval is designed to be used only for global code definitions.
actually see here, perhaps some people feel that the problem is too easy to solve the point, hehe, but found that this method is to need some luck and skill:
(1) for IE browser, the default already provides such a function: ExecScript, used in the global space to execute code, just know not many people.
(2) for the Firefox browser, the Eval function is called directly, then executes in the caller's space, if the call to Window.eval is performed in the global space. The person who knows is probably even less. After all, alert (eval==window.eval) returns true!
The features of the Eval function in Firefox are really surprising, but they can also be found from the JavaScript specification:
If value of the Eval property is used on any-to-than a direct call (which is, and other than by the explicit use of its
name as an Identifier which was the memberexpression in a callexpression), or if the Eval property was assigned to,
An Evalerror exception is thrown.
This means that the Eval function's execution is related to the caller, but does not say that it is executing the context. Therefore, IE and Firefox is the right one, it is difficult to say, we know the solution is good.

JavaScript eval () function

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.