DrillLab
第 27 / 105 道27 / 105 · #292

什么是高阶函数

What is a higher order function

先自己答,再往下看Answer it yourself first

一句话:参数里接收函数,或者返回一个函数—— 满足任一条就是高阶函数。

你天天在用:map / filter /reduce / forEach /sort(接收函数),setTimeout / addEventListener(接收函数),bind(返回函数)。

返回函数那一类才是考点, 因为它是柯里化、防抖节流、 和 React HOC 的共同底子:

会追问:「写一个防抖」—— 这是最常见的现场编码题, 本质就是「返回一个函数 + 闭包记住 timer」。 注意清理和 this 转发, 很多人会漏。

In one line: it takes a function as an argument, or it returns one — either one on its own makes it a higher order function.

You use them every day: map / filter / reduce / forEach / sort (they take a function), setTimeout / addEventListener (they take a function), and bind (it returns one).

The returning kind is what gets tested, because it is the shared foundation under currying, debounce and throttle, and React HOCs:

Follow-up: “Write a debounce” — the most common live-coding task there is, and at heart it is just “return a function and let the closure remember the timer”. Watch out for clearing the previous timer and forwarding this; plenty of people drop those.

JavaScript高阶函数的三种典型形态Three typical shapes of a higher-order function示意Illustrative
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};