← 回到书房大厅Esc

FROM THE BOOKSHELF / A PAGE TO KEEP

技术
39 分钟

执行上下文与调用栈

胡新宇

发布于 2026-05-21

本文系统讲解 JavaScript 执行上下文(全局、函数、Eval)的创建与销毁时机,调用栈的工作原理与栈溢出预防,变量对象 VO/AO 的生命周期与作用域链查找机制,以及尾调用优化 TCO 在 V8、SpiderMonkey、JavaScriptCore 中的差异。

执行上下文与调用栈

全局/函数/Eval 上下文的创建与销毁时机;变量对象(VO/AO)与作用域链的演变;调用栈(Call Stack)的隐式限制与尾调用优化(TCO)的现实境况。


目录

  1. 执行上下文 (Execution Context)
  2. 调用栈 (Call Stack)
  3. VO/AO 与作用域链
  4. 栈溢出与尾调用优化
  5. 实战案例
  6. 深度追问

执行上下文

什么是执行上下文?

执行上下文(Execution Context, EC)是代码执行时的环境快照,包含:

  • VO (Variable Object) / AO (Activation Object) —— 变量及函数声明的容器
  • 作用域链 (Scope Chain) —— 变量查找的链路
  • this 绑定 —— 执行主体

三种上下文类型

1. 全局执行上下文 (Global EC)

// 浏览器环境
console.log(this); // Window
console.log(globalThis); // Window

// Node.js 环境
console.log(this); // Module exports object
console.log(globalThis); // Object

创建时机: 脚本加载时立即创建 销毁时机: 页面卸载 / 进程退出 VO: 全局对象(window / global / globalThis)

2. 函数执行上下文 (Function EC)

function foo(a, b) {
  var c = a + b;
  console.log(c);
}

foo(1, 2);

创建时机: 函数调用时 销毁时机: 函数返回时 AO (Activation Object):

  • 函数参数:a=1, b=2
  • 本地变量:c=3
  • arguments 对象
  • this 指向

3. Eval 执行上下文

var x = 10;

function test() {
  var x = 20;
  eval('console.log(x)'); // 20
  eval('var y = 30;');
  console.log(y); // 30(污染了函数作用域)
}

test();
console.log(typeof y); // "undefined" (Node.js) 或 "number" (严格模式)

⚠️ 避免使用 eval() —— 安全风险、性能问题、作用域污染


调用栈

什么是调用栈?

调用栈(Call Stack)是一个 后进先出 (LIFO) 的数据结构,记录函数调用序列。

可视化栈操作

function a() {
  console.log('a 开始');
  b();
  console.log('a 结束');
}

function b() {
  console.log('b 开始');
  c();
  console.log('b 结束');
}

function c() {
  console.log('c 开始');
  console.log('c 结束');
}

a();

调用栈演变:

初始状态:
┌─────────────────┐
│  Global Stack   │
└─────────────────┘

a() 被调用:
┌─────────────────┐
│   a() Context   │
├─────────────────┤
│  Global Stack   │
└─────────────────┘

b() 被调用:
┌─────────────────┐
│   b() Context   │
├─────────────────┤
│   a() Context   │
├─────────────────┤
│  Global Stack   │
└─────────────────┘

c() 被调用:
┌─────────────────┐
│   c() Context   │
├─────────────────┤
│   b() Context   │
├─────────────────┤
│   a() Context   │
├─────────────────┤
│  Global Stack   │
└─────────────────┘

通过错误栈追踪

function test() {
  throw new Error('堆栈跟踪');
}

function wrapper() {
  test();
}

wrapper();

// 输出:
// Error: 堆栈跟踪
//     at test (<file>:2:11)
//     at wrapper (<file>:6:3)
//     at <anonymous> (<file>:9:1)

VO/AO 与作用域链

变量对象的生命周期

进入执行上下文阶段(函数调用但代码未执行)

function test(a, b) {
  var c = 1;
  var d = function() {};
  function e() {}
}

test(10, 20);

AO 结构:

AO = {
  // 1. 形参
  a: 10,
  b: 20,
  
  // 2. 函数声明(整体提升)
  e: <function reference>,
  
  // 3. 变量声明(仅声明,值为 undefined)
  c: undefined,
  d: undefined,
  
  // 4. arguments 对象
  arguments: { 0: 10, 1: 20, length: 2 }
}

执行阶段(代码逐行执行)

AO = {
  a: 10,
  b: 20,
  c: 1,                    // ← 赋值
  d: <function reference>, // ← 赋值
  e: <function reference>,
  arguments: { 0: 10, 1: 20, length: 2 }
}

作用域链的构建

var global_var = '全局';

function outer() {
  var outer_var = '外层';
  
  function inner() {
    var inner_var = '内层';
    console.log(inner_var);   // ✓ 在 inner AO 中
    console.log(outer_var);   // ✓ 通过作用域链查找
    console.log(global_var);  // ✓ 继续沿链查找
  }
  
  inner();
}

outer();

inner 的作用域链:

innerScope = [innerAO, outerAO, globalVO]
                ↓        ↓         ↓
              [变量]  [变量]   [全局变量]

变量查找过程(左到右):

  1. 在 innerAO 中查找 global_var —— ✗ 未找到
  2. 在 outerAO 中查找 —— ✗ 未找到
  3. 在 globalVO 中查找 —— ✓ 找到 '全局'

栈溢出与尾调用优化

栈溢出 (Stack Overflow)

每次函数调用都会占用栈内存。调用过深导致内存耗尽:

// ❌ 错误案例:无限递归导致栈溢出
function infiniteRecursion() {
  return infiniteRecursion(); // RangeError: Maximum call stack size exceeded
}

infiniteRecursion();

// ✓ 测试栈深度限制
let depth = 0;
function measureStackDepth() {
  depth++;
  try {
    measureStackDepth();
  } catch (e) {
    console.log(`栈深度限制: ${depth}`); // 通常 10000-15000
  }
}

measureStackDepth();

尾调用优化 (Tail Call Optimization, TCO)

尾调用(Tail Call): 函数的最后一条语句是另一个函数调用

✗ 非尾调用(无法优化)

function f(x) {
  return g(x) + 1; // 返回值需要加 1,还有计算
}

✓ 尾调用(可优化)

function f(x) {
  return g(x); // 直接返回,无后续操作
}

ES6 严格模式下的尾调用优化

'use strict'; // 必须开启严格模式

function factorial(n, acc = 1) {
  if (n <= 1) return acc;
  return factorial(n - 1, n * acc); // 尾调用
}

console.log(factorial(1000)); // 不会栈溢出(支持 TCO 的引擎)

现实情况:

引擎TCO 支持备注
V8 (Chrome/Node.js)❌ 不支持社区一直有争议
SpiderMonkey (Firefox)✓ 支持严格模式下默认启用
JavaScriptCore (Safari)✓ 支持性能最优

实战案例

案例 1:闭包与 AO 的延迟释放

function createCounter() {
  let count = 0; // AO 中的变量
  
  return function() {
    return ++count; // 闭包保持对 AO 的引用
  };
}

const counter1 = createCounter();
const counter2 = createCounter();

console.log(counter1()); // 1 → counter1 拥有独立的 AO
console.log(counter1()); // 2
console.log(counter2()); // 1 → counter2 拥有另一个独立的 AO
console.log(counter1()); // 3

内存占用:

  • 每个 counter 都保持一个 createCounter 的 AO 副本
  • 在 counter 被垃圾回收前,AO 不会释放

案例 2:函数表达式的变量提升

console.log(typeof fn1); // "function"
console.log(typeof fn2); // "undefined"

function fn1() {} // 函数声明 → 完整提升

var fn2 = function() {}; // 函数表达式 → 仅声明提升,值为 undefined

进入上下文时 AO:

AO = {
  fn1: <function reference>,
  fn2: undefined
}

案例 3:this 的动态绑定

const obj = {
  value: 42,
  
  getValueArrow: () => {
    console.log(this.value); // ❌ undefined(箭头函数继承外层 this)
  },
  
  getValueNormal: function() {
    console.log(this.value); // ✓ 42(普通函数 this 为 obj)
  },
  
  nested: {
    value: 100,
    method: function() {
      console.log(this.value); // ✓ 100(this 为 nested)
    }
  }
};

obj.getValueArrow();   // undefined
obj.getValueNormal();  // 42
obj.nested.method();   // 100

深度追问

Q1: 为什么函数表达式中的 name 属性只在函数内部有效?

const fn = function namedFunc() {
  console.log(typeof namedFunc); // "function"
};

console.log(typeof namedFunc); // "undefined"

原因: namedFunc 仅在函数 AO 中,不在外层作用域

Q2: 为什么 arguments 对象在箭头函数中不存在?

const arrow = () => {
  console.log(arguments); // ReferenceError: arguments is not defined
};

function normal() {
  console.log(arguments); // Arguments { 0: 1, 1: 2 }
}

normal(1, 2);

原因: 箭头函数没有独立的 AO,继承外层作用域

Q3: 为什么块级作用域内的 let/const 不被提升?

console.log(x); // ReferenceError: Cannot access 'x' before initialization

{
  let x = 10;
}

原因: let/const 存在"暂时性死区(TDZ)",进入块作用域后立即初始化但不赋值


总结表格

特性全局 EC函数 ECEval EC
创建时机脚本加载函数调用eval() 执行
VO/AO全局对象函数 AO当前 EC 的 AO/VO
thisWindow/Global取决于调用方式继承外层 this
作用域链[VO][AO, outer AO, ..., VO]当前 EC 链
销毁程序终止函数返回eval 结束

进阶阅读