当前位置:网站首页>JS stack memory
JS stack memory
2022-06-24 01:00:00 【ruochen】
1. Basic stack memory evaluation
The output of the following question is ?
let a = {n : 1
}
let b = a
a.x = a = {n: 2
}
console.log(a.x) // undefined
console.log(b) // { n: 1, x: { n: 2 } }Perform process analysis :
a = {n: 1}, First create an address in heap memory ( such as :AAAFFF00), The content isn: 1, Then in the global execution contextEC(G)Global variables environment inVO(G), Create global variablesa, Point to the heap memory address :AAAFFF00b = a, Empathy , In the global variable environmentVO(G)Create a global variableb, Point to the heap memory address :AAAFFF00a.x = a = { n: 2 }, Priority of this , In fact, it is equivalent toa.x = {n: 1},a = {n: 1}a.x = {n: 1}, Create another address in heap memory ( such as :AAAFFF11), The content isn: 1, stayaMemory address ofAAFF00Create axVariable , Point toAAAFFF11, here ,b = a = {n:1, x: {n: 1}}a = {n: 1}, takeaIs directed byAAAFFF00Change it toAAAFFF11
So the end result is :
b = {n:1, x: {n: 1}}
a = {n: 1}
2. Abnormal variable elevation
Variable Promotion : Before the current context executes , Will be able to var/function Declare or define promotion , belt var Only declare , belt function Statement of + Definition
But if you meet {} Block level scope , New and old browsers behave differently ( compatible ES3、 compatible ES6)
- IE browser <=IE10( The old version )undefined No matter
{}, As alwaysfunctionStatement + Definition , And there will be no block level scope - New version of browser ( there
{} Is divided by... In the object {})undefined{}Mediumfunction, In the global context, only declare that it is no longer defined ;undefined{}It appears thatfunction/let/const, A block level scope will be created
Let's take a question to illustrate :
var a = 0
if(true) {a = 1
function a() {}a = 21
console.log(a) // 21
}
console.log(a) // 1
If it's in IE10 following Implementation process of :
- Variable Promotion function a() {}
- Global variable promotion var a
- Start execution , overall situation a = 0
- overall situation a = 1
- overall situation a = 21
- Print global a: 21
- Print global a: 21
If you are in a new version of the browser , That is, forward compatibility ES3, Backward compatibility ES6 Implementation process of :
- Because the variables go up , therefore
var a,function aIn the global execution contextEC(G)Global variables environment inVO(G)Create a global variable ina - Code execution
a = 0, Global variable environmentVO(G)ina = 0 - encounter
{}Block level scope , Generate a block level execution contextEC(block), Will generate a private variable objectAO(block) - In this block-level scope , Because there is
function a, So variable promotion occurs at the block level , Statement + Definition , stayheapGenerate a function in heap memory , stayAO(block)Create a variableaPoint to function heap memory , After that, in this level , EncounteredaIt's all private
image.png
- Block level
a = 1,AO(block)ina = 1
image.png
- encounter
function a() {}, Because this function , For forward compatibilityES3, Therefore, it has been promoted once in the overall situation ; For backward compatibilityES6, Promote again in the block level scope , therefore Browsers for compatibility , When you really encounter a function at the block level , It will do one thing : Before encountering this code , Will put the code before all the right a The operation of , Map to a global , But the latter will not be dealt with , It will think that everything after this is private , Beforea = 1Will be mapped to the globalVO(G) in a =1
image.png
- after
a = 21, It is already private , So only block level is affectedAO(block) in a = 21
image.png
- In block level
console.log(a) => AO(block) a => 21 - Global
console.log(a) => VO(G) a => 1
Extended exercises
To deepen this perverse rule , Let's do a few more questions :
Abnormal lifting exercises 1
{ function foo() {}foo = 1
}
console.log(foo);
- The first 1 Step :
{}Mediumfunction fooIn variable Promotion , Declare only in global , Does not define
EC(G):
AO(G) function foo
- The first 2 Step , stay
{}There are... In the block levelfunction, So a block level scope will be generatedEC(Block),fooIn this block level scope , Variable Promotion : Statement + Definition
EC(block):
AO(block): funciont foo() {}- The first 3 Step , Start execution ( After the execution process ,
AO The variable object=>VO Activate the object), becausefooBoth global and private are declared , For compatibilityES3andES6, In carrying out thefunction foo() {}in , The previous operations are mapped to the global , That is to sayAO(block): funciont foo() {}Statement + The process of definition
EC(G):
VO(G) function foo() {}- The first 4 Step , perform foo = 1, Because there are... In the block level scope foo Private variables , So it's in EC(block) Assignment in
EC(block):
VO(G) foo => 1
Abnormal lifting exercises 2
Now I will start to be lazy , Ha ha ha , Please understand the following annotation steps according to the context
// The first 1 Step ,EC(G), AO(G): function foo
// The first 2 Step ,EC(block), AO(block): foo => function foo() {}// The first 3 Step , Start execution ,EC(G), VO(G): foo => function foo() {}// The first 4 Step ,foo = 1, EC(block), VO(block): foo => 1
// The first 5 Step ,EC(G), VO(G): foo => 1
{ function foo() {}foo = 1
function foo() {} // 1}
console.log(foo); // 1
Abnormal lifting exercises 2
// The first 1 Step ,EC(G), AO(G): function foo
// The first 2 Step ,EC(block), AO(block): foo => function foo() {}// The first 3 Step , Start execution function foo() {},EC(G), VO(G): foo => function foo() {}// The first 4 Step ,foo = 1, EC(block), VO(block): foo => 1
// The first 5 Step ,function foo() {} => EC(G), VO(G): foo => 1// The first 6 Step ,foo = 2,EC(block), VO(block): foo => 2
{ function foo() {}foo = 1
function foo() {}foo = 2
console.log(foo); // 2
}
console.log(foo); // 1
3. Stack memory with formal parameters
The output of the following function is ?
var x = 1
function func(x, y = function func2() { x = 2 }) {x = 3;
y()
console.log(x) // 2
}
func(5)
console.log(x) // 1
Let's use the diagram to analyze the process :
- Global execution
x = 1, stayEC(G)Create aVO(G), Create values 1, Create another objectx,x Point value 1
image.png
- Found function declaration , Create a heap memory for it , Define its functions , In this memory , Declare its scope , The global scope
VC(G), Shape parameterx、y, And its function body string , And create afunc, Point to this heap memory
image.png
- perform
func(5), Execute a function , A private execution context will be created for itEC(func), A private variable environment will be created in itAO(func) - stay
EC(func)Initial its scope chain : Its own scopeEC(func)And its parent scopeEC(G)( Global scope ) - Parameter assignment : Yes
x = 5,yNo ginseng , So use its default valuefunction func2, Encounter a function , Apply heap memory for itAAAFFF111, Again , Analyze its scope and formal parameters , And save the function body to memory , And willy Point to AAAFFF111
image.png
- After analyzing the relationship , Start execution
func5The body of the function x = 3, In your own scopeEC(func)Search for x, Found privatex, So willxPoint to 3y(), In your own scopeEC(func)Search fory, Found to haveyPoint tofunc2, Execute functionfunc2, And it creates a separate execution contextEC(func2), Analyze the scope chain for it , Own scopeEC(func2)And its parent scopeEC(func), Because it has no formal parameter assignment , Therefore, no private variables are created
image.png
- Start function
func2Function body ,x = 2, So in its own scopeEC(func2)The variable cannot be found inx, Will report to its parent scopeEC(func)Search for , Found to havex, So willEC(func)inxPoint to2
image.png
func2end of execution , Carry onEC(func)Mediumconsole.log(x), Output its ownx:2funcend of execution , Carry onEC(G)Mediumconsole.log(x), Output GlobalVO(G)Mediumx:1
image.png
4. Abnormal version of stack memory with formal parameter function
The output of the following topic is ?
var x = 1
function func(x, y = function func2() { x = 2 }) {// here ,x More than a var Statement
var x = 3;
y()
console.log(x)
}
func(5)
console.log(x)
Here we will talk about the browser running es6 The mechanism of the :
ES6 There are two cases where block level scopes are generated
The first 1 Kind of , natural {} The resulting block level scope
This is what we usually know ,ES6 There is a block-level scope in , As long as {}( Except for the {}) appear let/const/function
The first 2 Kind of , It is generated by the browser at runtime , That is, as long as the following two conditions are met :
- Function has a default value assigned to any formal parameter
- A variable has been declared separately in the function body (
var/let/const/functionAll count )undefined Then this function will produce 2 Context (s) :
* One is the private context generated by the execution of the function itself , For example, above `func` Function execution time , Will generate `EC(FUNC)` * One is the block level context enclosed by function body braces `EC(BLOCK)`
below , We still draw pictures to analyze :
- First process , And the last question 1\2 The steps are consistent , The global execution context is still generated
EC(G), It's inVO(G)Declare two variables :xandfunc,xPoint value 1,funcPoint to function heap memoryAAAFFF000
image.png
- Second process , perform
func(5), At this time , becausefuncMesomorphic parameterySet default value , And the variable... Is declared in the function bodyvar x = 3, According to the above rules , Two execution contexts are generated hereEC(FUNC)andEC(BLOCK) - Let's analyze it first
EC(FUNC), Its scope isEC(G), The scope chain is its own contextEC(FUNC)And the parent scope contextEC(G), Its formal parameter isx => 5,y => function func2 Heap memory AAAFFF111
image.png
4. Yes EC(BLOCK) Code block analysis , Its scope is EC(FUNC), The scope chain is its own context EC(BLOCK) And the superior execution context EC(FUNC), At the block level ,`var
x = 3 It states x, therefore x Is a private variable in the block level scope , When executed x = 3 when , In the block level x => 3`
image.png
- Carry on
y(), No... Found in block levelyVariable , Go to its scope chain superiorEC(FUNC)look for , eurekay, performy(), Generatefunc2Execution contextEC(FUNC2), Its scope isEC(FUNC), So the scope chain is[ Own execution context EC(FUNC2), Scope EC(FUNC)], No formal parameter and variable declarations , So there is no own private variable ; Execute the inner function bodyx = 2, stayEC(FUNC2)I can't find it in China.x, So go to its scope superior to findEC(FUNC),EC(FUNC)There isx, So willEC(FUNC)inx => 2
image.png
EC(BLOCK)Carry onconsole.log(x), Print isEC(BLOCK)In privatex, namely3func(5)completion of enforcement , Continue toEC(G)inconsole.log(x), Print isVO(G)Mediumx, namely1
image.png
therefore , The answer is 3 and 1
below , To prove that I'm not talking nonsense ='=, We debug the last question on the browser
- Make a breakpoint at the beginning debugger, Open in browser , because window Too many global variables , It's hard to find the overall situation
VO(G)Ofx, So I amWatchAdded inwindow.xVariable , It's convenient for us to observeVO(G)in ( That's the browser'sGlobal)xValue , You can see , Before debugging , In the overall situationxyesundefind
// The first 4 topic : Abnormal stack evaluation with formal parameters
debugger;
var x = 1
function func(x, y = function func2() { x = 2 }) {var x = 3;
y()
console.log(x)
}
func(5)
console.log(x)
image.png
- When performing the
x=1when ,func(5)Before execution , You can see the overall situationVO(G)Ofx = 1
image.png
- So let's keep going
func(5), You can see the birthScopein , That is to sayEC(FUNC)In the scope of , Generate two execution contextsBLOCKandLOCAL, Corresponding to what we said aboveEC(BLOCK)andEC(FUNC), Because there are... In the private variablesx, Then there are declarations at the block levelx, So it will be privatexMap to... In the block levelx
image.png
- Execute block level
var x = 3, Find private variables in the block levelxTurn into3
image.png
- perform
y(), Generation func2 Execution contextEC(FUNC2), Because there are no private variables , So itsLocalIt's empty
image.png
- After execution
y()inx = 2after , noticeEC(FUNC)Mediumx => 2
image.png
- perform
EC(BLOCK)inconsole.log(x), The output isBlockMediumx
image.png
- perform
EC(G)inconsole.log(x), The output isGlobalMediumx
image.png
thus , The above analysis conclusion is verified .
边栏推荐
- Empty encoded password警告原因
- An accident caused by a MySQL misoperation, and the "high availability" cannot withstand it!
- 想开户炒股,通过网上进行股票开户安全吗?-
- Activity 的 36 大难点,你会几个?,安卓面试2020
- Efficient integration of heterogeneous single cell transcriptome with scanorama
- 【SPRS J P & RS 2022】小目标检测模块:A Normalized Gaussian Wasserstein Distance for Tiny Object Detection
- Shardingsphere-proxy-5.0.0 implementation of capacity range partition (V)
- 13 `bs_ duixiang. Tag tag ` get a tag object
- C语言:递归实现N的阶乘
- C language: sorting with custom functions
猜你喜欢
![2022 postgraduate entrance examination experience sharing [preliminary examination, school selection, re examination, adjustment, school recruitment and social recruitment]](/img/05/e204f526e2f3e90ed9a7ad0361a72e.png)
2022 postgraduate entrance examination experience sharing [preliminary examination, school selection, re examination, adjustment, school recruitment and social recruitment]

Mip-NeRF:抗混叠的多尺度神经辐射场ICCV2021

应用配置管理,基础原理分析

13 `bs_duixiang.tag标签`得到一个tag对象

GNN upper edge distributor! Instead of trying to refine pills, you might as well give your GNN some tricks

Real time computing framework: Flink cluster construction and operation mechanism

【小程序】实现双列商品效果

What problems need to be solved by MES management system in the era of intelligent manufacturing

实时计算框架:Flink集群搭建与运行机制
![[machine learning] linear regression prediction](/img/74/9b5067bb9057049c998898ff2457f1.png)
[machine learning] linear regression prediction
随机推荐
Isn't this another go bug?
Cvpr2022 𞓜 thin domain adaptation
C language: on the right shift of matrix
[technology planting grass] on the "double 11" of this year, Tencent cloud lightweight servers will be collected in a fair manner
Real time computing framework: Spark cluster setup and introduction case
阿里巴巴面试题:多线程相关
Alibaba interview question: multi thread related
CVPR2022 | 可精简域适应
现在网上开股票账户安全吗?选择国有券商,最快8分钟开户成功
WinSCP和PuTTY的安装和使用
C language: structure array implementation to find the lowest student record
Building a digital software factory -- panoramic interpretation of one-stop Devops platform
Use recursion to form a multi-level directory tree structure, with possibly the most detailed notes of the whole network.
Security | warm tips: security incidents on the cloud have intensified recently. Please do a good job in backup monitoring of cloud security protection!
解决base64压缩文件,经过post请求解压出来是空格的问题
应用配置管理,基础原理分析
飞桨产业级开源模型库:加速企业AI任务开发与应用
[Hongke case] how can 3D data become operable information Object detection and tracking
Social order in the meta universe
kubernetes之常用核心资源对象