Table of contents
2. Stack memory and heap memory
3. Execution stack calling process
Preface: Because some students often confuse stack memory, heap memory, and execution stack, I wrote this article to distinguish them. Before understanding related concepts, we must first understand the data types of JS
1. JS data types
JS data types are divided into two categories: primitive types and reference types
Primitive types include:
primitive type |
typeof return type |
null |
object |
undefined |
undefined |
boolean |
boolean |
number |
number |
bigint |
bigint |
string |
string |
symbol |
symbol |
We will find that the null type returns the object type after executing typeof . This is because in JS, if the first three digits of the binary are all 0, it will be judged as the object type, and the binary representation of null is all 0, so naturally the first three digits are also 0. So when typeof is executed, object will be returned
There is only one Object type for reference types
2. Stack memory and heap memory
1.StackStack
The stack is a first-in-last-out data structure with the same exit and entry. Memory space is automatically allocated to store the addresses of original data types and reference data types.
2.Heap
The heap is an unordered data structure stored in key-value pairs. It dynamically allocates memory and is used to store values of reference data types.
3. Execution stack (JS stack)
1. Execution stack
Definition: The call stack of the execution context .
2. Execution context
Definition: A piece of code in a variable object . Each context is associated with a variable object. All variables and functions defined in the context exist on this object.
Execution context is divided into global execution context , function execution context , and eval() function execution context.
Global execution context : There is only one, created when the program is run for the first time. It will create a global object (window object) in the browser and make this point to this global object.
Function execution context (there can be multiple): It will be created when the function is called; a new execution context will be created every time the function is called.
eval() function execution context : JavaScript's eval() function will create its own execution context when executing its internal code (rarely used and not recommended)
// 1.进入全局上下文执行环境
function a() {
console.log('a函数执行环境');
b(); // 3.进入b函数上下文执行环境
console.log('a函数执行环境'); // 4.b函数执行完成后,返回a函数上下文执行环境
}
function b() {
console.log('b函数执行环境');
}
a(); // 2.进入 a 函数上下文执行环境
console.log('全局上下文'); // 5.a 函数执行完成后,返回 全局上下文执行环境;如果没有其他代码需要执行,则执行栈会把 全局执行上下文 从执行栈中弹出
// 最终打印结果:
// a函数执行环境
// b函数执行环境
// a函数执行环境
// 全局上下文执行环境
a function execution environment |
|
b function execution environment |
|
Global context execution environment |
|
3. Execution stack calling process