当前位置:网站首页>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 .
边栏推荐
- 现在网上开股票账户安全吗?选择国有券商,最快8分钟开户成功
- 飞桨产业级开源模型库:加速企业AI任务开发与应用
- [technique of planting grass] spit blood and clean up, and take you to collect goose feathers in a fancy way! Do not spread!!!
- [applet] realize the effect of double column commodities
- Grab startup logcat
- [technology planting grass] on the "double 11" of this year, Tencent cloud lightweight servers will be collected in a fair manner
- 一次 MySQL 误操作导致的事故,「高可用」都顶不住了!
- C语言:结构体数组实现找出最低分学生记录
- If you want to open an account for stock trading, is it safe to open an account online-
- Is it safe to open a stock account online now? Select a state-owned securities firm, and the fastest time to open an account is 8 minutes
猜你喜欢
![[machine learning] linear regression prediction](/img/74/9b5067bb9057049c998898ff2457f1.png)
[machine learning] linear regression prediction

Open source model library of flying propeller industry: accelerating the development and application of enterprise AI tasks

The concept of TP FP TN FN in machine learning

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

【机器学习】线性回归预测

paddle使用指南

MIP nerf: anti aliasing multiscale neural radiation field iccv2021

【Redis进阶之ZipList】如果再有人问你什么是压缩列表?请把这篇文章直接甩给他。

Use recursion to form a multi-level directory tree structure, with possibly the most detailed notes of the whole network.

【虹科案例】3D数据如何成为可操作的信息?– 对象检测和跟踪
随机推荐
numpy. linalg. Lstsq (a, B, rcond=-1) parsing
C language: structure array implementation to find the lowest student record
Dart series: using generators in dart
Installation and use of winscp and putty
[image detection saliency map] calculation of fish eye saliency map based on MATLAB distortion prompt [including Matlab source code 1903]
苹果Iphone14搭载北斗导航系统,北斗VS GPS有哪些优势?
【ICCV Workshop 2021】基于密度图的小目标检测:Coarse-grained Density Map Guided Object Detection in Aerial Images
How many of the 36 difficult points of activity do you know?, Android interview 2020
数字化工厂可以分为哪两类
利用Scanorama高效整合异质单细胞转录组
[SPRS J P & RS 2022] small target detection module: a normalized Gaussian Wasserstein distance for tiny object detection
一次 MySQL 误操作导致的事故,「高可用」都顶不住了!
WinSCP和PuTTY的安装和使用
用一个软件纪念自己故去的母亲,这或许才是程序员最大的浪漫吧
Using anydesk remote control for intranet penetration horizontal movement
[redis advanced ziplist] if someone asks you what is a compressed list? Please dump this article directly to him.
跨域和JSONP
Experience summary of 9 Android interviews, bytes received, Ali, advanced Android interview answer
CVPR2022 | 可精简域适应
C语言:关于矩阵右移问题