当前位置:网站首页>JS parsing and execution process
JS parsing and execution process
2022-04-23 17:40:00 【Lost Camel】
Reprinted from :https://www.cnblogs.com/foodoir/p/5977950.html
Parsing and execution processes in the global
Preprocessing : Create a lexical environment (LexicalEnvironment, It is abbreviated as LE), scanning JS Functions declared in a declarative way in , use var Define the variables and add them to the Lexical Environment in the preprocessing stage .
One 、 How to understand preprocessing in the global environment
For example, the following code :
var a = 1;// use var Variables defined , To assign
var b;// use var Variables defined , Unassigned
c = 3;// Undefined , Direct assignment
function d(){// Functions declared in a declarative way
console.log('hello');
}
var e = function(){// Function expression
console.log('world');
}
During preprocessing, the lexical scope it creates can be expressed as :
LE{ // At this time LE amount to window
a:undefined
b:undefined
No, c
d: A reference to a function
No, e
}
emphasize :1、 Preprocessing function must be JS Functions declared declaratively in ( Not a function expression ), Look at examples :
d();
e();
function d(){// Functions declared in a declarative way
console.log('hello');
}
var e = function(){// Function expression
console.log('world');
}
The output is :hello; Report errors e is not a function
2、 Yes, it is var Variables defined , Look at examples :
console.log(a);//undefined
console.log(b);//undefined
console.log(c);// Report errors :c is not defined
var a = 1;
var b;
c = 3;
Two 、 Handling of naming conflicts
Look at the following code : What do you think the output is ?
console.log(f);
var f = 1;
function f(){
console.log('foodoir');
}
console.log(f);
function f(){
console.log('foodoir');
}
var f = 1;
console.log(f);
var f = 1;
var f = 2;
console.log(f);
function f(){
console.log('foodoir');
}
function f(){
console.log('hello world');
}
You may be the same as I started , I think the output is foodoir, So you're wrong , You should continue to look at the preprocessing problem mentioned earlier . The output of the first piece of code should be :function f(){console.log('foodoir');}.
See the second code , You may answer without thinking, and the result is 1, And you tell me why javascript The functions inside are not overloaded in the traditional sense . Yes javascript The functions inside are not overloaded , But the result of the second code is still :function f(){console.log('foodoir');}.( The reason will be explained later )
If you still think the result of the third code is 2 Or is it 1, So I suggest you go back to the previous example of preprocessing . The result of the third paragraph is :undefined.
The result of the fourth code is function f(){console.log('hello world');}
reason : When there is a conflict in the declaration of the processing function , Will be covered ; When there is a conflict between variable declarations , Will ignore . When there are both function declarations and variable declarations , You can be like me CSS To understand the weight in , Function declarations are always weighted higher , So the end result is often a reference to a function declaration .
3、 ... and 、 Execution of global functions
Let's look at the following example :
1 console.log(a);
2 console.log(b);
3 console.log(c);
4 console.log(d);
5 var a = 1;
6 b = 2;
7 console.log(b);
8 function c(){
9 console.log('c');
10 }
11
12 var d = function(){
13 console.log('d');
14 }
15 console.log(d);
1、 Let's first analyze the global preprocessing , give the result as follows :
LE{
a:undefined
No, b
c: A reference to a function
d:undefined
}
here , We can get the first four lines of code, and the results are :
undefined
Report errors
function c(){console.log('c');
undefined
2、 After preprocessing , The code starts to be parsed step by step ( Comment out the error code in the second line )
In the 6 Line code execution completed ,LE Medium a The value of a 1;
LE{
a:1
No, b
c: A reference to a function
d:undefined
}
The first 7 Line code execution completed ,LE There is b Value ( And b The value of is 2, here b The value of becomes a global variable directly );
LE{
a:1
b:2
c: A reference to a function
d:undefined
}
The first 10 Line code execution completed ,
LE{
a:1
b:2
c: Pointing function
d:undefined
}
The first 14 Line code execution completed , here
LE{
a:1
b:2
c: Pointing function
d: Pointing function
}
About b An example of becoming a global variable , We enter... In the console window.b, You can get b As the result of the 2.
The result is shown in Fig. :

Add : Use lexical scope , We can well explain the example of a function with multiple parameters passing only one parameter .
function f(a,b){
}
f(1);
Its lexical scope can be explained in this way :
LE{
a:1
b:undefined
}
Parsing and execution process in function
The difference between parsing and execution in functions is not very big , But there is one in the function arguments We need to pay attention to , Let's look at the following example :
function f(a,b){
alert(a);
alert(b);
var b = 100;
function a(){}
}
f(1,2);
Let's first analyze the preprocessing of the function , It is similar to global preprocessing , Its lexical structure is as follows :
LE{
b:2
a: A reference to a function
arguments:2
}
//arguments, The number of parameters actually called when calling the function
Combined with the previous sentence : When there is a conflict in the declaration of the processing function , Will be covered ; There was a conflict when processing variable declarations , Will ignore .
So the results are :function a(){} and 2
When the parameter value passed in has one :
function f(a,b){
alert(a);
alert(b);
var b = 100;
function a(){}
}
f(1);
The lexical structure at this time is as follows :
LE{
b:undefined
a: A reference to a function
arguments:1
}
So the results are :function a(){} and undefined
There is also a place to pay attention to : If it doesn't work var Declared variables , Will become the most external LE Members of , Global variables
function a(){
function b(){
g = 12;
}
b();
}
a();
console.log(g);//12
Console results :

With the foundation in front , We can be right JS Have a deep understanding of the scope and scope chain of .
About JS Scope and scope chain
console.log(a);//undefined
console.log(b);//undefined
console.log(c);//c is not defined
console.log(d);//d is not defined
var a = 1;
if(false){
var b = 2;
}else{
c = 3;
}
function f(){
var d = 4;
}
With the above foundation, we can easily get the results of the first three , But there is much doubt about the fourth , This is the time , You need to take a look at javascript Knowledge about scope .
In programming languages , Scope can generally be divided into four categories : Block level scope 、 Function scope 、 dynamic scope 、 Lexical scope ( Also known as static scope )
Block level scope
On the other C In class languages , The part enclosed in braces is called scope , But in javascript There is no block level scope , Let's take the following example :
for(var i=0;i<3;i++){
//
}
console.log(i);
The result is 3, reason : After execution for After the cycle , At this time i The value of is 3, Still valid in the future
Function scope
There is no scope for pure functions
dynamic scope
Let's look at the following example :
function f(){
alert(x);
}
function f1(){
var x = 1;
f();
}
function f2(){
var x = 1;
f();
}
f1();
f2();
If there is a dynamic scope , Then the results should be 1、2, But the end result is not what we want , The result is :x is not defined. therefore javascript There is no dynamic scope
Lexical scope ( Also known as static scope )
We can declare one at the beginning of the function x=100
var x=100;
function f(){
alert(x);
}
function f1(){
var x = 1;
f();
}
function f2(){
var x = 1;
f();
}
f1();
f2();
The result is two separate pops 100. explain javascript The scope of is static , analysis :
function f(){
alert(x);
}
// f [[scope]] == LE == window
// Create a scope object f [[scope]], It is equal to the lexical environment when it was created LE( According to the previous knowledge, we can know that the lexical environment at this time is equal to window)
function f1(){
var x = 1;
f();// When it's actually implemented ( Look up step by step )LE ->f.[[scope]] == window
}
In the lexical analysis stage , The relevant scope has been determined . Scope also forms a related chain , We call it scope chain . Let's look at the following example :
function f(){
alert(x);
}
// f [[scope]] == LE == window
// Create a scope object f [[scope]], It is equal to the lexical environment when it was created LE( According to the previous knowledge, we can know that the lexical environment at this time is equal to window)
function f1(){
var x = 1;
f();// When it's actually implemented ( Look up step by step )LE ->f.[[scope]] == window
}
The final result is :100
Let's take a classic example :
// Define global variables color, For the whole world , That is, global variables can be used anywhere color
var color = "red";
function changeColor(){
// stay changeColor() The function defines local variables anotherColor, Function only changeColor() It works inside
var anotherColor = "blue";
function swapColor(){
// stay swapColor() The function defines local variables tempColor, Function only swapColor() It works inside
var tempColor = anotherColor;
anotherColor = color;
color = tempColor;
// You can visit here color、anotherColor and tempColor
console.log(color); //blue
console.log(anotherColor); //red
console.log(tempColor); //blue
}
swapColor();
// You can only visit here color, Cannot access anotherColor、tempColor
console.log(color); //blue
console.log(anotherColor); //anotherColor is not defined
console.log(tempColor); //tempColor is not defined
}
changeColor();
// You can only visit here color
console.log(color); //blue
console.log(anotherColor); //anotherColor is not defined
console.log(tempColor); //tempColor is not defined
The other thing to note is that :new Function The situation is different
var x= 123;
function f(){
var x = 100;
//g.[[scope]] == window
var g = new Function("","alert(x)");
g();
}
f();
// The result is :123
Summary :
With f1{ f2{ x}} For example , expect x, First of all, I will find... In the Lexical Environment in the function , Not found yet. Go to the lexical environment of the parent function to find …… Until window Look for .
Now , The problem is coming. ....
problem 1: So far, it seems that if there are multiple functions that want a variable , It's so troublesome to write one every time , Do we have any way to be lazy ?
Method : Set the variable as a global variable
problem 2: Don't you mean to reduce the use of global consumption ? Because when we do large projects, it is inevitable to introduce multiple JS library , The naming of variables may conflict , And it is not easy to find after an error , What should we do at this time ?
Method : Set the variable to a value function in , Like the following :
function(){
var a = 1;
var b = 2;
function f(){
alert(a);
}
}
problem 3: In your way, we can't access it outside , What do I do ?
Method : We use anonymous functions , Examples are as follows :
(function(){
var a = 1,
b = 2;
function f(){
alert(a);
}
window.f = f;
})();
f();
// The result is :1
版权声明
本文为[Lost Camel]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230552420809.html
边栏推荐
- [binary number] maximum depth of binary tree + maximum depth of n-ary tree
- MySQL installation
- 圆环回原点问题-字节跳动高频题
- 2. Electron's HelloWorld
- How does matlab draw the curve of known formula and how does excel draw the function curve image?
- Collection of common SQL statements
- 122. The best time to buy and sell stocks II - one-time traversal
- ASP. Net core configuration options (Part 2)
- 239. Maximum value of sliding window (difficult) - one-way queue, large top heap - byte skipping high frequency problem
- Excel quickly and automatically fills the contents of a row on a blank cell
猜你喜欢

.Net Core3. 1 use razorengine NETCORE production entity generator (MVC web version)

In embedded system, must the program code in flash be moved to ram to run?

Simulation of infrared wireless communication based on 51 single chip microcomputer

92. 反转链表 II-字节跳动高频题

flink 学习(十二)Allowed Lateness和 Side Output

How to change input into text

超分之TDAN

Understanding of RPC core concepts

Double pointer advanced -- leetcode title -- container with the most water

PC uses wireless network card to connect to mobile phone hotspot. Why can't you surf the Internet
随机推荐
2.Electron之HelloWorld
Read software engineering at Google (15)
394. String decoding - auxiliary stack
Seven cattle upload pictures (foreground JS + background C API get token)
Halo 开源项目学习(二):实体类与数据表
Use of todesk remote control software
[WPF binding 3] listview basic binding and data template binding
Flash project cross domain interception and DBM database learning [Baotou cultural and creative website development]
.Net Core3. 1 use razorengine NETCORE production entity generator (MVC web version)
双指针进阶--leetcode题目--盛最多水的容器
C dapper basically uses addition, deletion, modification and query transactions, etc
剑指 Offer 03. 数组中重复的数字
Clickhouse table engine
ros常用的函数——ros::ok(),ros::Rate,ros::spin()和ros::spinOnce()
In embedded system, must the program code in flash be moved to ram to run?
Solution of Navicat connecting Oracle library is not loaded
Perception of linear algebra 2
402. Remove K digits - greedy
ASP. Net core JWT certification
Using quartz under. Net core -- a simple trigger of [7] operation and trigger