调用栈
JavaScript Call Stack
tip
调用栈用于 跟踪JavaScript引擎 在调用多个函数的代码中 的位置,它包含有关当前正在运行的函数以及从该函数中调用了哪些函数的信息。
此外,JavaScript engine uses a call stack to manage execution contexts. JavaScript引擎使用调用栈管理执行上下文(Global execution context、function execution contexts)
The call stack uses the stack data structure that works based on the LIFO (last-in-first-out) principle.
When you execute a script, the JavaScript engine creates a global execution context and pushes it on top of the call stack.
Whenever a function is called, the JavaScript engine creates a function execution context for the function, pushes it on top of the call stack, and starts executing the function.
If a function calls another function, the JavaScript engine creates a new function execution context for the function being called and pushes it on top of the call stack.
When the current function completes, the JavaScript engine pops it off the call stack and resumes the execution where it left off. 当当前函数完成时,JavaScript 引擎将其从调用栈中弹出并从中断处继续执行。
The script will stop when the call stack is empty.
function add(a, b) {
return a + b;
}
function average(a, b) {
return add(a, b) / 2;
}
let x = average(10, 20);
当 JavaScript 引擎执行上述脚本时,它会将全局执行上下文(由 main() 或 global() 函数表示)放在调用栈上。
The global execution context enters the creation phase and moves to the execution phase.
JavaScript 引擎执行对 average(10, 20) 函数的调用,并为 average() 函数创建一个函数执行上下文,并将其压入调用栈的顶部。
JavaScript 引擎开始执行 average(), 因为 average() 函数位于调用栈的顶部
average() 函数调用 add() 函数。此时,JavaScript 引擎为 add() 函数创建另一个函数执行上下文,并将其放在调用栈的顶部
JavaScript 引擎执行 add() 函数并将其从调用栈中弹出
此时,average() 函数位于调用栈的顶部,JavaScript 引擎执行它并将其弹出调用栈。
1. 栈溢出(Stack overflow)
The call stack has a fixed size, depending on the implementation of the host environment, either the web browser or Node.js. 调用栈具有固定大小,具体取决于主机环境的实现,Web 浏览器或 Node.js。
If the number of execution contexts exceeds the size of the stack, a stack overflow error will occur. 如果执行上下文的数量超过栈的大小,则会发生栈溢出错误。
例如,when you execute a recursive function that has no exit condition, the JavaScript engine will issue a stack overflow error 当你执行一个没有退出条件的递归函数时,JavaScript 引擎会发出堆栈溢出错误
function fn() {
fn();
}
fn(); // Uncaught RangeError: Maximum call stack size exceeded 超出最大调用栈大小
2. Asynchronous JavaScript
JavaScript is a single-threaded programming language. This means that the JavaScript engine has only one call stack. Therefore, it only can do one thing at a time. JavaScript 是一种单线程编程语言。这意味着 JavaScript 引擎只有一个调用栈。因此,它在一个时间点只能做一件事。
When executing a script, the JavaScript engine executes code from top to bottom, line by line. In other words, it is synchronous. 执行脚本时,JavaScript 引擎从上到下逐行执行代码。换句话说,它是同步的。
Asynchronous means the JavaScript engine can execute other tasks while waiting for another task to be completed. 异步意味着 JavaScript 引擎可以在等待另一个任务完成的同时执行其他任务。To do this, the JavaScript engine uses an event loop. 为此,JavaScript 引擎使用事件循环。