执行上下文栈(Execution Context Stack)是JavaScript运行时管理执行上下文(execution context)的一种数据结构,它遵循"Last In, First Out"(后进先出) 的原则,每当函数调用时,新的执行上下文被创建并推入栈顶,而在函数执行完成后,对应的执行上下文从栈顶弹出。
下面用代码来模拟一下具体的执行过程:
function outer() {
console.log("Outer function");
inner();
}
function inner() {
console.log("Inner function");
}
outer();
上面这段代码在执行过程中会经历以下阶段:
- 全局执行上下文创建阶段:
- 创建全局执行上下文,将其推入执行上下文栈
Execution Context Stack:
-------------------------
| Global Context |
-------------------------
- 全局执行上下文执行阶段
- 调用
outer()函数 - 创建
outer()函数执行上下文,将其推入执行上下文栈
- 调用
Execution Context Stack:
-------------------------
| Outer Context |
| Global Context |
-------------------------
- outer函数执行上下文执行阶段
- 执行
console.log("Outer function") - 调用
inner()函数 - 创建
inner()函数执行上下文,将其推入执行上下文栈
- 执行
Execution Context Stack:
-------------------------
| Inner Context |
| Outer Context |
| Global Context |
-------------------------
- inner函数执行上下文执行阶段
- 执行
console.log("Inner function")
- 执行
- inner函数执行完成:
- 将
inner函数执行上下文从栈顶弹出
- 将
Execution Context Stack:
-------------------------
| Outer Context |
| Global Context |
-------------------------
- outer函数执行完成:
- 将
outer函数执行上下文从栈顶弹出
- 将
Execution Context Stack:
-------------------------
| Global Context |
-------------------------
- 全局执行完成
- JavaScript程序执行完成
以上就是执行上下文栈运行的整体流程,执行上下文栈的运行机制确保了函数调用的嵌套顺序和正确的上下文管理。栈的结构让引擎能够按照正确的顺序管理执行上下文,确保函数执行完成后能够回到正确的上下文。