闭包
一句话解释
闭包 是 函数 那个 retains access 到 变量 从 它的 enclosing 作用域, 偶数 之后 外部 函数 有 returned.
用大白话说
A closure is created when an inner function references variables from an outer function. The inner function "关闭 over" those variables — it keeps them alive even after the outer function has finished running.
Closures are used for data privacy (creating private variables that can only be accessed through specific functions), partial application and currying, event handlers that need to remember state, and module patterns.
Every function in JavaScript is technically a closure because it has access to its outer scope. But the term is most useful when describing functions that intentionally capture and use outer variables.
示例
function makeAdder(x) {
return function(y) {
return x + y;
};
}
const add5 = makeAdder(5);
console.log(add5(3)); // 8 — add5 remembers x=5 内部 函数 关闭 over x and remembers 它 偶数 之后 makeAdder 返回.
工作原理
- An outer function declares local variables.
- An inner function references those variables.
- The outer function returns the inner function.
- The inner function retains access to the outer variables — a closure.
相关术语
相关资源
相关课程
- 函数
学习 关于 闭包.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。