← 中文资源

简体中文版本

循环闭包捕获的是绑定不是值

var 在整个循环里只有一个绑定,回调拿到的是循环结束后的最终值;let 每轮迭代生成新绑定,闭包捕获当轮的值,IIFE 正是把每轮包进独立作用域的老式修法。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

var sees 3
var sees 3
var sees 3
let sees 0
let sees 1
let sees 2
iife sees 0
iife sees 1
iife sees 2

实现说明

核心工作在嵌套循环里完成:外层 for (var i = 0; i < 3; i++),内层 for (let n = 0; n < 3; n++)。

使用要点

  • 每一步打印都带着自己的标签:var sees、let sees、iife sees。

常见问题

依赖情况复杂吗?

一点也不复杂:零依赖,没有要锁版本或审计的东西。

代码示例

// A closure captures the binding itself, not a copy of the value.
// var declares ONE function-scoped binding for the whole loop, so by
// the time the callbacks run, every one of them sees the final value.
for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log('var sees', i), 0);
}

// let creates a fresh binding per iteration; each callback captures
// the binding of its own iteration and sees that iteration's value.
for (let n = 0; n < 3; n++) {
  setTimeout(() => console.log('let sees', n), 0);
}

// The pre-let fix did the same thing by hand: an IIFE gives each
// iteration its own scope, so captured is a per-iteration binding.
for (var j = 0; j < 3; j++) {
  ((captured) => setTimeout(() => console.log('iife sees', captured), 0))(j);
}