A detailed description of the eval () function in JavaScript

Source: Internet
Author: User
Tags define local variable scope

Like many other explanatory languages, JavaScript can also interpret strings that run from JavaScript source code and produce a value. JavaScript uses the global function eval () to do this work

Eval ("1+2"),-> 3

Dynamically judging the strings in the source code is a very powerful language feature, and almost no need to be applied in practice. If you use eval (), you should carefully consider whether you really need to use it.

First, eval () is a function or an operator

Eval () is a function, but because it has been treated as an operator: Earlier versions of the JavaScript language defined the Eval function, and the modern JavaScript interpreter performed a lot of code analysis and optimization. The problem with Eval is that code for dynamic execution is usually not parsed, in other words, if a function calls Eval, then the interpreter will not be able to further refine the function, while another problem with defining eval as a function is that it can be given other names, Var f=eval Then the interpreter cannot rest assured of optimizing any function that calls F (). And when Eval is an operator, you can avoid these problems.

Second, eval ()

Eval () has only one parameter. If the passed parameter is not a string, it returns the function directly. If the argument is a string, it compiles the string as a JavaScript code if the compiler loser throws a syntax error exception. If the compilation succeeds, it starts execution of this piece of code and returns the last expression in the string or the value of the statement, and eventually returns undefined if the last expression or statement has no value. If the string throws an exception, the exception will pass the call to Eval ().

The most important thing about Eval is that it uses a variable scope environment that calls it. That is, it looks for the value of the variable and the operation that defines the new variable and function is exactly the same as the code in the local scope. If a function defines a local variable x and then calls eval ("X"), it returns the value of the local variable. If it calls eval ("X=1"), it changes the value of the local variable. If the function calls eval ("Var y=2;"), it declares a new local variable y, and similarly, a function can declare a local variable with the following code:

Eval ("function f () {return x+1;}");

If you call eval in the topmost code, it will, of course, be used for global variables and global functions.

It is important to note that the string passed to Eval must pass through the syntax and cannot be arbitrarily pasted into the function by eval, for example: eval ("return;") is meaningless, because return only works in the function, and in fact, the context of the Eval string execution is the same as the context of the calling function, which cannot be run as part of the function. If the string is semantic as a separate script, then passing it to eval as a parameter is perfectly fine, otherwise, Eval throws a syntax error exception.

Iii. Global eval ()

Eval () has the ability to change layout variables, which is a big problem for the JavaScript optimizer. As a workaround, however, the JavaScript interpreter does not have many optimizations for the functions that call eval. But when the script defines an alias for Eval and calls it with another name, how does the JavaScript interpreter work? To simplify the implementation of the JavaScript interpreter, the ECMASCRIPT3 standard specifies that no interpreter is allowed to give an alias to Eval. If the Eval function is called by an alias, a Eavlerror exception is thrown.

In fact, most implementations do not do so. When called by an alias, Eval executes its string as the top-level global code. The code executed may define new global variables and global functions, or assign values to global variables, but cannot use or modify local variables in the keynote function, so this does not affect code optimization within the function.

ECMASCRIPT5 is against the use of Eavlerror and regulates the behavior of eval, "direct eval", which is often referred to as "direct eval" when the Eval () function is called directly using an unqualified "eval" name. When you call Eval () directly, it is always executed within the context scope that called it. Other indirect calls use global objects as their context scopes, and cannot read, write, and define local variables and functions. Here's a sample code:

varGeval=eval;//calling Evla with an alias will be the global evalvarx= "Global", y= "global";//Two Global variablesfunctionF () {//local eval is performed within the function    varx= "Local";//Defining local VariablesEval ("x + = ' chenged ';");//values of local variables that are changed directly using eval    returnX//returns the changed local variables}function g () {//the global eval is performed within this function.    vary= "Local"; Geval ("Y + = ' changed ';");//direct call changes the value of a global variable    returny;}            Console.log (f (), x); //changed layout, output "local changed global"Console.log (g (), y);//changed global variables, output "local global changed"

The global eval of these behaviors is not just a compromise in the need for code optimization, it is actually a very useful feature that allows us to execute global scripting snippets that do not have any dependencies on the context. It is not uncommon for a scenario that really requires eval to execute a code snippet. But when you are really aware of its necessity, you are more likely to use global eval instead of local eval.

Iv. Strict eval ()

ECMAScript5 Strict mode imposes more restrictions on the behavior of the eval () function, and even imposes restrictions on the use of the identifier eval. When Eval is lowered in strict mode, or the code snippet executed by eval starts with the "use strict" instruction, Eval here is a local eval in the private context. That is, in strict mode, the code snippet executed by eval can query or change a local variable, but cannot define a new variable or function in the local scope.

In addition, strict mode lists "eval" as a reserved word, which makes eval () more like an operator. You cannot overwrite the eval () function with an alias. and the variable name, the function name. function parameters or exception-caught parameters cannot be named Eval.

As the saying goes: Bao Jianfeng from sharpening out, plum blossom fragrance from bitter cold.

Source: http://www.jb51.net/article/40780.htm

A detailed description of the eval () function in JavaScript

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.