柯里化是将多参函数转为单参函数链,核心是固定参数、延迟执行;通用实现用fn.length判断调用时机,闭包缓存参数,支持this绑定;适用于预设配置、事件处理、函数组合等场景。
函数柯里化(Currying)是将一个接收多个参数的函数,转换为一系列只接收一个参数的函数的过程。核心不是“拆参数”,而是“固定部分参数、延迟执行”,最终返回结果。
最简实用版实现(支持不定参数、自动判断调用时机):
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) {
return fn.apply(this, args);
} else {
return function
(...moreArgs) {
return curried.apply(this, args.concat(moreArgs));
};
}
};
}说明:
柯里化不是炫技,它在真实开发中解决几类典型问题:
const request = curry((baseUrl, timeout, path) => fetch(`${baseUrl}/${path}`, { timeout }));
const githubApi = request('https://api.github.com', 5000);
githubApi('users').then(...); // 自动带上 baseUrl 和 timeoutconst handleClick = curry((userId, e) => console.log(`User ${userId} clicked`));
btn.addEventListener('click', handleClick(123))
const add = curry((a, b) => a + b);
const multiply = curry((a, b) => a * b);
const inc = add(1);
const double = multiply(2);
compose(double, inc)(5); // → 12
柯里化不是万能的,用错场景反而增加理解成本:
Math.max(1,2,3) 柯里化后变成 curry(Math.max)(1)(2)(3),既难读又无收益它不复杂但容易忽略——真正价值在于让参数流更可控、逻辑更可组合、复用更自然。