闭包
函数那个 retain access 到它们的 lexical 作用域, 启用私有状态 and factories.
你将学到
- 什么闭包是 and 如何 lexical 作用域是 preserved
- 创建私有变量使用闭包
- Factory 函数 and 部分 application
- Memoization 使用闭包 for 缓存
- 常见 pitfalls: 闭包 in 循环 and memory considerations
概念讲解
The Core Idea
closure 是 the combination of a function and the lexical environment in which it was created. When an inner function is returned from an outer function, it carries a reference to the outer function's variables — even after the outer function has finished executing. The variables are not copied; they are kept alive by the closure's reference to them.
This is a natural consequence of lexical scoping, not a special feature. Every function in JavaScript is technically a closure over its surrounding scope. The pattern becomes visible when you deliberately return a function that uses variables from an outer scope.
Private State
Closures are the traditional way to create private variables in JavaScript. By declaring a variable inside a factory function and returning methods that read or write it, you hide the variable from the outside. Only the returned functions can access it. This is the module pattern and the basis of encapsulation before private class fields existed.
Factory Functions and Partial Application
A closure can capture arguments and produce a new, specialized function. makeAdder(10) returns a function that adds 10 to whatever you pass it. This is partial application — fixing some arguments now and supplying the rest later. It is the foundation of currying and many functional utilities.
Memoization
Closures can cache expensive results. A memoized function stores a map of inputs to outputs in its closure. On subsequent calls with the same input, it returns the cached value instead of recomputing. This trades memory for speed and is a classic optimization for pure functions.
The Loop Pitfall
A famous historical bug involved closures in loops with var. Because var is function-scoped, all closures in the loop shared the same variable, which ended at its final value. let fixes this by creating a fresh binding per iteration. Always use let (or const) in loops that create closures.
示例代码
// Private state with a closure — the balance is hidden
function createAccount(initialBalance) {
let balance = initialBalance;
return {
deposit(amount) {
balance += amount;
return balance;
},
withdraw(amount) {
if (amount > balance) throw new Error("Insufficient funds");
balance -= amount;
return balance;
},
getBalance() {
return balance;
},
};
}
const account = createAccount(100);
account.deposit(50);
console.log(account.getBalance()); // 150
// console.log(balance); // ReferenceError — balance is private
// Factory / partial application
const multiply = (a) => (b) => a * b;
const double = multiply(2);
const triple = multiply(3);
console.log(double(5), triple(5)); // 10 15
// Memoization with a closure
function memoize(fn) {
const cache = new Map();
return (arg) => {
if (cache.has(arg)) return cache.get(arg);
const result = fn(arg);
cache.set(arg, result);
return result;
};
}
const slowSquare = memoize((n) => {
console.log("computing for", n);
return n * n;
});
console.log(slowSquare(4)); // computes
console.log(slowSquare(4)); // cached — no "computing" log
Demonstrates 私有状态 (bank account 使用隐藏 balance), 部分-application factory (multiply), and memoize higher-顺序函数那个 caches results in 它的闭包.
动手试一试
- Math Evaluator
闭包经常 wrap math — evaluate 内部 computations live.
- JSON Formatter
Inspect cached 数据结构闭包 maintain.
常见错误
错误写法
创建闭包 in 循环使用 var and sharing one 变量
正确做法
var 是函数-scoped, 所以每个闭包 shares 相同变量. Use let (or const) in 循环, 哪个创建 fresh binding 每 iteration and gives 每个闭包它的 own 值.
错误写法
Accidentally keeping 大对象 alive 通过闭包 (memory leak)
正确做法
闭包持有引用到 它的整个作用域. 如果你 capture 大对象, 它 cannot 是 garbage-collected. 发布引用通过设置它们到 空 or narrowing 闭包到 仅什么它 需要.
相关资源
相关速查表
- JavaScript Cheatsheet
闭包模式, 模块模式, and memoization.
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。