1// 返回函数:一个能记住次数的计数器
2function makeCounter() {
3 let n = 0; // 被闭包保住
4 return () => ++n;
5}
6const next = makeCounter();
7next(); next(); // 2
8
9// 高频现场题:防抖
10function debounce(fn, delay = 300) {
11 let timer = null; // 闭包里的状态
12 return function (...args) {
13 clearTimeout(timer); // 每次进来先撤销上一次
14 timer = setTimeout(() => fn.apply(this, args), delay);
15 }; // 用 function 而不是箭头,才能转发 this
16}
17
18// React 的 HOC 也是高阶函数:收组件、返组件
19const withLogger = (Comp) => (props) => {
20 console.log("render", Comp.name);
21 return <Comp {...props} />;
22};
1// Returning a function: a counter that remembers its count
2function makeCounter() {
3 let n = 0; // kept alive by the closure
4 return () => ++n;
5}
6const next = makeCounter();
7next(); next(); // 2
8
9// A very common live-coding question: debounce
10function debounce(fn, delay = 300) {
11 let timer = null; // state that lives in the closure
12 return function (...args) {
13 clearTimeout(timer); // every call first cancels the previous one
14 timer = setTimeout(() => fn.apply(this, args), delay);
15 }; // use function, not an arrow, to forward this
16}
17
18// A React HOC is a higher-order function too: takes a component, returns a component
19const withLogger = (Comp) => (props) => {
20 console.log("render", Comp.name);
21 return <Comp {...props} />;
22};