Home Web Front-end JS Tutorial Detailed explanation of eval() function in JavaScript_Basic knowledge

Detailed explanation of eval() function in JavaScript_Basic knowledge

May 16, 2016 pm 05:24 PM
eval javascript

eval(“1 2”),-> 3

Dynamically determining strings in source code is a very powerful language feature that is almost unnecessary to apply 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 it has been treated as an operator. . 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 It only plays a role in the function, and in fact, the context when the eval string is executed is the same as the context in which the function is called, which 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 JavaScript optimizers. 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.

Actually, 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:

Copy code The code is as follows:

var geval=eval; //Calling evla using an alias will be a global eval
var x="global",y="global"; //Two global variables
function f() {                                                                                                                                                                                                                       Value
return x; //Return the changed local variable
}
Function g(){ //The global eval is executed in this function ("y = ' changed';"); // Directly call the value of the global variable
return y;
}
console.log(f(),x); // Change the layout Changed, output "local changed global"
console.log(g(),y); //Changed the global variable, output "local global changed"


These global eval Behavior is not just a compromise between the needs of code optimization, it is actually a very useful feature that allows us to execute global script code segments without any 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. Additionally, 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 edge of a sword comes from sharpening, and the fragrance of plum blossoms comes from the bitter cold.

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles