


JavaScript cheats lexical eval, with and catch and their performance issues
Normally speaking, the scope chain of the execution context will not change
The lexical scope in JavaScript is not static
(lexical scope/static scope: The scope is determined by the function declaration position when writing the code)
There are several mechanisms that can deceive the lexicon
They are with(), eval() and the catch clause of the try-catch statement
where with We should not use eval and eval (it will cause a lot of problems)
Cheating lexical means cheating lexical scope
In other words, they change the scope chain at runtime
Let me talk about it below These mechanisms that can deceive lexicon
eval
eval() function accepts a string as a parameter, and parses the string to generate code
var a = 123;eval('console.log(a)');// 123
So the console printed 123
After executing the eval function
The js engine does not know that this code was dynamically inserted and the scope chain was modified
The engine will also look for the scope chain as usual
Look at the following code
var a = 1;function demo(){ eval('var a = 2;');//欺骗词法 console.log(a);// 2} demo();
When the eval function is executed, the variable a is added to the top scope of the demo function execution environment
a in this local environment "shadows" a in the global environment
Eventually causes the program to print 2
The eval() function can not only modify the scope it is currently in, but can even modify the global scope
No matter what, it can modify the lexical scope during runtime
ES5's strict mode adds some restrictions to this function. I added the local strict mode to the above code
var a = 1;function demo(){ 'use strict'; eval('var a = 2;'); console.log(a);// 1} demo();
We found that this time the console printed 1
This is because in strict mode, eval() has its own independent lexical scope when running (to save it from messing up the scope chain of the execution environment)
In this way, the declaration in it cannot modify the scope in which it is located
This can There are two other ways to dynamically generate code that are very similar to it
The first parameter of timers setTimeout() and setInterval() can be a code string
The same is true for the last parameter of function constructor new Function() Accepting code strings
is the same as eval(). Do not use this usage. This will cause serious performance problems. We will discuss this issue later.
with
Another one is not recommended. The deceptive lexical syntax is the with keyword
with is usually used as a shortcut to repeatedly reference multiple properties of an object
The advantage is that there is no need to repeatedly reference the object itself
For example, I want to reuse console object
console.log(1);console.info(2);console.warn(3);
Use the with keyword
with(console){ log(1); info(2); warn(3); }
It seems that there is no problem with with, but looking at the following
function demo(obj){ with(obj){ a = 5; } }var obj1 = {a:1};var obj2 = {b:2}; demo(obj1); console.log(obj1.a);// 5demo(obj2); console.log(obj2.a);// undefinedconsole.log(a);//5 -->变量a居然泄漏到了全局环境
we find that using with The keyword modifies the a of obj1
But not only does it not add a to obj2, but it produces side effects and leaks to the global
This is because with can process an object into a completely isolated lexical scope (put it in the scope The front of the domain chain)
So execution occurs inside it a = 5;
It will look down the scope chain, but not found, so a variable a is created globally ( No declaration of var)
Note: Although with creates a lexical scope, normal var declarations inside with will not be restricted to this block scope
That is to say, declarations outside with Scope
Like this
function demo(){ var obj = {}; with(obj){ var b = 1; console.log(b); // 1 } console.log(b); // 1} demo(); console.log(b);// Uncaught ReferenceError: b is not defined
And the with keyword is simply not allowed to be used in the strict mode of ES5
If you try to use it, you will see an error like this:
catch
In addition to eval and with, the catch clause in the try-catch statement can also modify the scope chain of the execution environment
When an error occurs in the try code block , the execution flow immediately jumps to the catch clause
Then the exception object is pushed into a mutable object and placed at the front of the scope chain, which is very similar to with
Once the catch clause is executed, The scope chain will be restored to its original state
But unlike eval and with, try-catch is still relatively useful and does not need to be abandoned completely (although I have not used it)
Performance
Deception of lexicon will cause performance problems
The js engine will perform performance optimization during the compilation phase. Many optimizations rely on the ability to perform static analysis based on code lexicon
The definition locations of variables and functions are determined in advance, so that the logo can be quickly found symbol
But eval or with cannot determine the position of the identifier (it exists during code execution and cannot be statically analyzed)
In other words: In front of eval and with, all the optimizations of the js engine are meaningless (Simply cool)
Since it makes no sense, the js engine simply won’t be optimized
This will cause the program to run slower
For with, it also has its own unique performance issues...
Generating a scope will cause all local variables of the function in which it is located to be in the second scope chain object
The access cost is higher
For the try-catch statement, if we want Use, you can do this
try{ ...}catch(e){ handleError(e); }
Only a piece of code is executed in the catch statement, and it is delegated to a function to handle errors
In this way, there is no access to local variables
Temporary changes in the scope chain will not Will affect performance
Summary
Summary the key points
Lexical scope means that the scope is determined by the position of the function declaration when writing the code
The compile-time lexical analysis phase can know where and how all identifiers are declaredeval can be evaluated on code strings, thereby modifying the lexical scope at runtime
with treats an object reference as a scope, This creates a lexical scope at runtime
eval will generate an independent lexical scope in strict mode, and the scope cannot be modified
with is prohibited from being used in strict mode
eval and with (and catch) can deceive the lexicon and modify the scope chain during execution
eval and with cause the js engine to be unable to optimize the scope search during the compilation phase (cannot be statically analyzed), causing the program to slow down.
Having said so much, I want to tell everyone not to use the with key Words and eval functions~( ̄0 ̄)/
The above is the content of JavaScript’s deceptive lexical eval, with and catch and its performance issues. For more related content, please pay attention to the PHP Chinese website (www.php.cn )!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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 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

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

As Vue becomes more and more widely used, Vue developers also need to consider how to optimize the performance and memory usage of Vue applications. This article will discuss some precautions for Vue development to help developers avoid common memory usage and performance problems. Avoid infinite loops When a component continuously updates its own state, or a component continuously renders its own child components, an infinite loop may result. In this case, Vue will run out of memory and make the application very slow. To avoid this situation, Vue provides a

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.

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

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

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).
