实现说明
核心工作在嵌套循环里完成:外层 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);
}