闭包定义
闭包是函数及其周围状态(词法环境)的引用,即使外部函数已返回,内部函数仍可访问外部变量。
function createCounter() {
let count = 0;
return function() {
count++;
return count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2高阶函数
接收函数为参数或返回函数的函数。
// map 高阶函数
[1, 2, 3].map(x => x * 2); // [2,4,6]
// 防抖(高阶函数)
function debounce(fn, delay) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
const log = debounce(() => console.log('输入完成'), 300);闭包常见用途
- 私有变量
- 函数工厂
- 事件处理中的状态保持
闭包是函数式编程的基石,但过度使用可能导致内存泄漏。
