Home >Web Front-end >JS Tutorial >Detailed code examples of how to use the global function eval() in JavaScript

Detailed code examples of how to use the global function eval() in JavaScript

伊谢尔伦
伊谢尔伦Original
2017-07-25 11:37:401471browse

Dynamic determination of strings in source code is a very powerful language feature, and it is almost unnecessary to apply it in practice. If you use eval(), you should carefully consider whether you really need to use it.

1. Is eval() a function or an operator?

eval() is a function, but because it has been regarded as an operation Fu came to treat. . Early versions of the JavaScript language defined the eval function, and modern JavaScript interpreters perform extensive code analysis and optimization. The problem with eval is that code used for dynamic execution generally cannot be analyzed. In other words, if a function calls eval, the interpreter will not be able to further optimize the function and define eval as another part of the function. The problem is that it can be given another name, var f=eval; then the interpreter cannot safely optimize any function that calls f(). When eval is an operator, these problems can be avoided.

2. eval()

eval() has only one parameter. If the parameter passed in is not a string, it returns this function directly. If the parameter is a string, it will compile the string as JavaScript code, and throw a syntax error exception if the compilation fails. If the compilation is successful, this piece of code will be executed and the value of the last expression or statement in the string will be returned. If the last expression or statement has no value, undefined will eventually be returned. If the 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 in which it is called. That is, it looks up the values ​​of variables and defines new variables and functions exactly the same as 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. Similarly, a function can declare a local variable through the following code:

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

If eval is called 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 eval must be grammatically consistent. You cannot paste arbitrary code snippets into the function through eval. For example: eval("return;") is meaningless. Because return only plays a role within a function, and in fact, the context in which eval's string is executed is the same as the context in which the function is called, this does not allow it to run as part of the function. If the string is semantic as a separate script, then there is no problem passing it to eval as a parameter, otherwise, eval will throw a syntax error exception.

3. Global eval()

eval() has the ability to change layout variables, which is a big problem for the JavaScript optimizer. However, as a stopgap measure, the JavaScript interpreter does not do much optimization for functions that call eval. But how does the JavaScript interpreter work when a script defines an alias for eval and calls it under another name? In order to simplify the implementation of JavaScript interpreters, the ECMAScript3 standard stipulates that no interpreter is allowed to assign aliases to eval. If the eval function is called through an alias, an EavlError exception will be thrown.

In fact, most implementations do not do this. When called through an alias, eval will execute its string as top-level global code. The executed code may define new global variables and global functions, or assign values ​​to global variables, but it cannot use or modify local variables in the calling function. Therefore, this will not affect code optimization within the function.

ECMAScript5 is against the use of EavlError and standardizes the behavior of eval, "direct eval". When the eval() function is called directly using the unqualified "eval" name, it is usually called "direct eval" ". When eval() is called directly, it is always executed within the scope of the context in which it is called. Other indirect calls use the global object as their context scope and cannot read, write, or define local variables and functions. Here is a sample code:

var geval=eval;                //使用别名调用evla将是全局eval
var x="global",y="global";    //两个全局变量
function f(){                //函数内执行的是局部eval
    var x="local";            //定义局部变量
    eval("x += ' chenged';");//直接使用eval改变的局部变量的值
    return x;                //返回更改后的局部变量
}
Function g(){                //这个函数内执行了全局eval
    var y="local";
    geval("y += ' changed';"); //直接调用改变了全局变量的值
    return y;
}
console.log(f(),x);            //改变了布局变了,输出 “local changed global”
console.log(g(),y);            //改变了全局变量,输出    “local global changed”

These behaviors of global eval are not just a compromise made for the need to optimize the code, it is actually a very useful feature that allows We execute global script snippets that have no dependencies on the context. There are very few scenarios where eval is really needed to execute a code segment. But when you really realize its necessity, you are more likely to use global eval instead of local eval.

4. Strict eval()

ECMAScript5 strict mode imposes more restrictions on the behavior of the eval() function and even on the use of the identifier eval. When eval is called in strict mode, or the code segment executed by eval begins with a "Use strict" directive, eval here is a local eval in the private context. That is, in strict mode, the code segment executed by eval can query or change local variables, but cannot define new variables or functions in the local scope.

In addition, strict mode lists "eval" as a reserved word, which makes eval() more like an operator. The eval() function cannot be overridden with an alias. And variable names, function names. Neither function parameters nor exception capture parameters can be named eval.

The above is the detailed content of Detailed code examples of how to use the global function eval() in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn