Eval () functions in JavaScript

Source: Internet
Author: User
Tags define local

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

The Dynamic Determination of strings in 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.

1. Whether eval () is a function or an operator

Eval () is a function, but it has been treated as an operator .. Early versions of JavaScript define eval functions, and modern JavaScript interpreters perform a lot of code analysis and optimization. The problem with eval is that the code used for dynamic execution cannot be analyzed. In other words, if a function calls eval, the interpreter cannot further optimize the function, another problem with defining eval as a function is that it can be assigned another name, var f = eval; then the interpreter cannot safely optimize any calls to f (). When eval is an operator, these problems can be avoided.

Ii. eval ()

Eval () has only one parameter. If the input parameter is not a string, it returns this function directly. If the parameter is a string, it will compile the string as JavaScript code. If the compilation fails, a syntax error is thrown. If the compilation is successful, run the code and return the value of the last expression or statement in the string. If the last expression or statement has no value, undefined is returned. If a string throws an exception, this exception will pass the call to eval ().

The most important thing about eval is that it uses the variable scope environment that calls it. That is to say, it looks for the value of the variable and defines the operation of the new variable and function, and the code in the Local scope is exactly the same. If a function defines a local variable x and calls eval ("x"), it returns the value of the local variable. If it calls eval ("x = 1"), it will change the value of the local variable. If the function calls eval ("var y = 2;"), it declares a new local variable y. Similarly, a function can declare a local variable using the following code:

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

If you call eval in the top-level code, of course, it will act on global variables and global functions.

It should be noted that the string passed to the eval must be syntactically passed, and the code snippet cannot be arbitrarily pasted into the function through eval, for example: eval ("return ;") it is meaningless, because return only plays a role in the function. In fact, the Context Environment of eval string execution is the same as that of function calling, this cannot be used as part of a function. If the string as a separate script has semantics, it is no problem to pass it to eval as a parameter. Otherwise, eval will throw a syntax error exception.

Iii. Global eval ()

Eval () has the ability to change layout variables, which is a big problem for JavaScript optimizers. However, as an alternative, the JavaScript interpreter does not do much Optimization for functions that call eval. But how does the JavaScript interpreter work when the script defines an eval alias and calls it with another name? To simplify the implementation of the JavaScript interpreter, the ECMAScript3 Standard specifies that no interpreter is allowed to assign aliases to eval. If the eval function is called using an alias, an EavlError exception is thrown.

In fact, most implementations do not. When called using an alias, eval regards its string as the top-level global code for execution. The executed code may define new global variables and global functions, or assign values to global variables, but it cannot use or modify the local variables in the main function. Therefore, this does not affect the code optimization in the function.

ECMAScript5 is opposed to the use of EavlError and standardizes eval behavior. "Direct eval", when the unlimitedly "eval" name is used directly to call the eval () function, it is usually called "direct eval ". When eval () is called directly, it is always executed within the context scope of the call. Other indirect calls use global objects as their context scopes, and cannot read, write, or define local variables and functions. The following is an example code:

Copy codeThe Code is as follows:
Var geval = eval; // call evla using an alias will be a global eval
Var x = "global", y = "global"; // two global variables
Function f () {// The local eval is executed in the function
Var x = "local"; // defines a local variable.
Eval ("x + = 'chenged';"); // directly use eval to change the value of a local variable
Return x; // return the changed local variable.
}
Function g () {// This Function executes the global eval
Var y = "local ";
Geval ("y + = 'changed ';"); // the value of the global variable is changed by calling directly.
Return y;
}
Console. log (f (), x); // the layout is changed, and "local changed global" is output"
Console. log (g (), y); // Changes the global variable and outputs "local global changed"

The global eval behavior is not only a compromise between the needs of code optimization, but also a very useful feature, it allows us to execute global script code segments that are not dependent on the context. Few scenarios require eval to execute code segments. But when you realize the necessity, you are more likely to use global eval instead of local eval.

Iv. Strict eval ()

The strict mode of ECMAScript5 imposes more restrictions on the behavior of the eval () function, and even limits the use of the identifier eval. When eval is called in strict mode, or the code segment executed by eval starts with the "Use strict" command, the eval here is a local eval in the private context. That is to say, in strict mode, code segments executed by eval can query or modify local variables, but new variables or functions cannot be defined in local scopes.

In addition, the strict mode columns "eval" as reserved words, which makes eval () more like an operator. Eval () functions cannot be overwritten with an alias. And variable name, function name. Function parameters or exception capture parameters cannot be named eval.

Bao Jianfeng from honed out, plum flowers from bitter cold.

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.