函数柯里化的概念,我相信很多人都很熟悉,但是具体什么时候会用到呢?
作用有哪些?
- 参数复用
- 延迟执行
- 动态创建
哪些使用场景?
针对它的三个作用点来举例说明下场景。
场景一:参数复用
需求:需要根据参数拼接出几个完整的地址,如:“juejin.cn/post/697868…
// 常规实现
function spliceUrl(protocol, hostname, patchname) {
return `${protocol}${hostname}${patchname}`;
}
const url1 = spliceUrl('https://', 'juejin.cn', '/post/6978685539985653767/');
const url2 = spliceUrl('https://', 'juejin.cn', '/post/6989751020255445005');
根据上面代码我们发现,参数protocol和hostname在每次调用时都会传参。
// currying写法
function spliceUrl(protocol, hostname) {
return function(patchname) {
return `${protocol}${hostname}${patchname}`;
}
}
const urlBase = spliceUrl('https://', 'juejin.cn');
const url1 = urlBase('/post/6978685539985653767/')
const url2 = urlBase('/post/6989751020255445005');
场景二:延迟执行
需求: 在实现一个求和函数的时候,希望传入的参数能满足sum(1)(2)(3)(4);
function currying(func) {
const args = [];
return function result(...rest) {
if (rest.length === 0)
return func(...args);
args.push(...rest);
return result;
}
}
const add = (...args) => args.reduce((a, b) => a + b);
const sum = currying(add);
console.log(sum(1)(2)(3)(4)()); // 10
场景三:动态创建
需求:使用监听事件时,判断浏览器兼容性
const whichEvent = (function() {
if (document.addEventListener) {
return function(element, event, handler) {
if (element && event && handler) {
element.addEventListener(event, handler, false);
}
};
} else {
return function(element, event, handler) {
if (element && event && handler) {
element.attachEvent('on' + event, handler);
}
};
}
})();
这样实现的好处是:这样其实就是提前确定了会走哪一个方法,避免每次都进行判断。