作用域

函数内部可以访问外部变量,但外部不能访问内部。查找变量按"作用域链"从内向外。

什么是闭包

函数 + 它创建时所在作用域的引用,合起来叫闭包。即使外部函数执行完,闭包仍能访问那些变量:

function makeCounter() {
  let count = 0;             // 私有变量
  return function() {
    count++;
    return count;
  };
}
const c = makeCounter();
c(); c(); c();               // 每次都能记住 count
// count 外部无法直接访问

实战:防抖

function debounce(fn, delay) {
  let timer = null;          // 闭包保存 timer
  return function(...args) {
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, args), delay);
  };
}
window.addEventListener('scroll', debounce(handler, 200));

实战:计数器(单例)

const counter = (() => {
  let i = 0;
  return { inc: () => ++i, get: () => i };
})();
counter.inc(); counter.inc();
counter.get(); // 2
注意:闭包持有引用会阻止 GC 回收,用完后把引用置 null 或避免长生命周期闭包持有大对象。