什么是高阶函数
What is a higher order function
一句话:参数里接收函数,或者返回一个函数—— 满足任一条就是高阶函数。
你天天在用: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.