当前位置:网站首页>An article understands variable lifting
An article understands variable lifting
2022-04-23 08:13:00 【Night runner】
Article transferred from : An article understands the variable Promotion (hoisting) - You know
the front
We are all concerned about the improvement of variables (hoisting
) It must be no stranger , This article hopes to establish a systematic rule , In the future, we will encounter variable Promotion , You can read this article again , Find the answer according to the rules in the text . Final , We can remember this rule , It's natural to understand that variables improve .
Example
I believe you are no stranger to this example :
a = 2;
var a;
console.log( a ); /// 2
Why is this passage a
You can assign values before you declare them ?
Take another look at this example :
console.log( a ); //undefined
var a = 2;
Why is this output undefined
Well ?
Don't worry , Read the whole article and you will know what rules to use to infer the results .
Scope analysis
We will not explain the scope in detail here , A scope can be thought of as a collection of accessible objects .
Let's make a popular analogy , Now there is an apartment management company , There are many apartments below . Senior administrator A
, He has the keys to all the apartments and all the rooms , So he can open all the apartments, all the rooms , And can take out all the articles in the room . Intermediate Administrator B
, Only the keys to all the rooms in an apartment , He can take out all the things in this apartment , But you can't take out the items of other apartments . The reason is that the Administrator B When taking things ( When a program executes code ), No information from other apartments ( Other scoped information ).
For simplicity , This article only covers... Under the same scope , The interaction of different scopes will be discussed in the next few articles
You can imagine entering the global scope or a function scope , The engine will produce a json object
As a database , Then the code will be executed from this json
Find value in .
var pseudoContext = {
}
JavaScript Parser
Generally speaking , You may think JavaScript The parser will be in run-time The runtime parses the code line by line .
In fact, when the interpreter reaches a scope , Will compile the code first , Then parse it line by line .
When JavaScript After the engine runs to a certain scope ( In the first example , The scope is global
Global scope )
It has two steps
1. Initialization phase ( Creation Stage) [ When entering a scope , Before running the code line by line ]
+ establish var
Variable , function
Functions and functions arguments
Parameters
2. Code execution phase (Activation/Code Execution Stage)
+ Assign values to variables and functions , And execute code
Initialization phase ( Creation Stage)
In the initialization phase , Occurs when you enter a scope :
1. If the scope is inside the function , Put the function parameters in the previouscontext json
in
2. Scan the current scope for functions :
+ Every function found , Just put the name and function pointer in the front json in
+ If the function name already exists , Overwrite the previous function pointer 3. Scan the current scope for variables :
+ Every variable foundvar
, Just put your name in the frontjson
in , And set the value to > becomeundefined
+ If the variable name already exists , Will not cover , Ignore and continue scanning
Code execution phase (Activation/Code Execution Stage)
Execute the code line by line , And before the assignment isundefined
The variable ofvar
Example 1
Let's go back to the previous example :
a = 2;
var a;
console.log( a ); /// 2
Let's apply the previous rules :
- First enter the global scope , Initialize an empty impersonation scope
json
- Before stepping through the code , Execute the initialization phase
- Scope is not inside a function , No function arguments , Ignore
- Scan found no function , Ignore
- Scan found variables
var a
, In the json Inside and set toundefined
- Now our
json
:
pseudoContext = {
a = undefined
}
a = 2
4. Scan complete , Execute the code line by line
a = 2
5. Scan our scope , Find out pseudoContext
In existence a
, Assigned as 2
pseudoContext = {
a = 2
}
6. next step :
console.log( a );
7. Scope of action pseudoContext
Find a
, Find value , Output 2
Example 2
console.log( a ); //undefined
var a = 2;
- First enter the global scope , Initialize an empty impersonation scope
json
- Before stepping through the code , Execute the initialization phase
- Scope is not inside a function , No function arguments , Ignore
- Scan found no function , Ignore
- Scan found variables
var a
, In the json Inside and set toundefined
- Now our
json
:
pseudoContext = {
variables: {
a = undefined
}
}
4. Scan complete , Execute the code line by line
console.log( a );
json
in a
yes undefined
, So the output undefined
A more complex example 3
console.log(typeof foo); // function pointer
console.log(typeof bar); // undefined
var foo = 'hello',
bar = function() {
return 'world';
};
function foo() {
return 'hello';
}
1. First enter the global scope , Initialize an empty impersonation scope json
2. Before stepping through the code , Execute the initialization phase
3. Scope is not inside a function , No function arguments , Ignore
4. Scan found function foo
( The first 9 That's ok ), Declare and assign values
5. At this time json:
pseudoContext = {
foo = function pointer
}
6. Scan found variables var foo
, because foo
The name already exists , According to the previous rules " If the variable name already exists , Will not cover , Ignore and continue scanning ", Ignore
7. Scan found variables var bar
, Assigned as undefined
The engine will scan the function first , Then variable scanning
8. Now our json
:
pseudoContext = {
foo = function pointer,
bar = undefined
}
Scan complete , Execute the code line by line
console.log(typeof foo);
json
in foo
yes function pointer
, return function
next step :
console.log(typeof bar);
json
in bar
yes undefined
, Output undefined
let
and const
I hope you can understand the above , Say again let
and const
, These two and var
Different They are in what is called Time static zone temporal dead zone (TDZ)
( I don't know who took the name of No. 2 middle school ).
- When entering a scope , We won't add it to our
json
in - In limine
get
perhapsset
It's a mistakeReferenceError
- When executing line by line , If there is
let
const
Statement , Will be in scopejson
Created in , If the assignment is , Will be in scopejson
Assignment in
b // Uncaught ReferenceError: b is not defined
let b =2
summary
I hope you have a deeper understanding of variable promotion after reading this article , Variable promotion is only superficial , Just one. js The parser and scope work together to produce a result . The scope will be explained in more detail later .
1 : Improve performance
Because there will be a code check and precompile during code execution ( Only once ), In this way, there is no need to check and re parse the code every time the function variable is executed ,
2: Fault tolerance improves
a=2;var a;console.log(a) //2
For example, such a piece of code , It is precisely because the prompt of the variable will not report an error during execution .
版权声明
本文为[Night runner]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230648423688.html
边栏推荐
- [untitled]
- BUFFCTF文件中的秘密1
- 扎心了!一女子发朋友圈羡慕别人按时发工资被开除,连点赞的同事也一同被开除了...
- 网赚APP资源下载类网站源码
- Upload labs range practice
- 访问数据库的时候出现错误 Operation not allowed for a result set of type ResultSet.TYPE_FORWARD_ONLY.详解
- 1216_ MISRA_ C standard learning notes_ Rule requirements for control flow
- 学fpga(从verilog到hls)
- CSV Column Extract列提取
- 求3个字符串(每串不超过20个字符)中的最大者。
猜你喜欢
thinkphp6+jwt 实现登录验证
校园转转二手市场源码下载
dried food! Point based: differentiable Poisson solver
每周leetcode - 06 数组专题 7~739~50~offer 62~26~189~9
Concours de compétences en informatique en nuage - - première partie de l'environnement cloud privé openstack
在MATLAB中快速画圆(给出圆心坐标和半径就能直接画的那种)
1216_ MISRA_ C standard learning notes_ Rule requirements for control flow
WordPress爱导航主题 1.1.3 简约大气网站导航源码网址导航源码
CSV Column Extract列提取
BUUCTF [ACTF2020 新生赛]Include1
随机推荐
CSV Column Extract列提取
sql 使用过的查询语句
一篇文章看懂变量提升(hoisting)
C outputs a two-dimensional array with the following characteristics.
数据安全问题已成隐患,看vivo如何让“用户数据”重新披甲
岛屿的个数
Summary of facial classics
Mobile terminal layout (3D conversion, animation)
Research on system and software security (3)
Research on system and software security (2)
[Effective Go 中文翻译]函数篇
Research on system and software security (I)
[programming practice / embedded competition] learning record of embedded competition (I): establishment of TCP server and web interface
使用 Ingress 实现金丝雀发布
室内定位技术对比
Jetson Xavier NX (3) bazel mediapipe installation
Dvwa 靶场练习记录
Samsung, March to the west again
Cloud computing skills competition -- the first part of openstack private cloud environment
利用sqlmap注入获取网址管理员账号密码