概述
以前听轮子哥说过,柯里化只不过是箭头函数的语法糖。觉得是有那么点意思,自己好像懂了。直到我看redux官方文档middleware,我才真正理解了为什么说柯里化是箭头函数的语法糖。于是记录下来,供以后开发时参考,相信对其他人也有用。
箭头函数的嵌套
redux官方文档middleware里面有这么一段代码:
const logger = store => next => action => {
console.log('dispatching', action)
let result = next(action)
console.log('next state', store.getState())
return result
}
当时看到这里我有点懵了,箭头函数还能这么写?有这么简洁优美的写法吗???然后继续看上下文,发现上面的代码是下面这段代码的简写形式:
function logger(store) {
return function wrapDispatchToAddLogging(next) {
return function dispatchAndLog(action) {
console.log('dispatching', action)
let result = next(action)
console.log('next state', store.getState())
return result
}
}
}
原来是这样啊!!!这就是箭头函数的嵌套,实际上就是柯里化!!!所以柯里化只不过是箭头函数的语法糖!!!
例子
举个例子,对于加法,我们可以这么写:
function add(a, b) {
return a + b;
}
但是我们用柯里化怎么写呢?
function add(a) {
return function(b) {
return a + b;
}
}
于是我们想怎么用就怎么用:
console.log(add(4)(5)); //输出9
const add4 = add(4);
console.log(add4(5)); //输出9
console.log(add4(6)); //输出10
但是呢,上面那段柯里化的代码很难懂啊,而且有嵌套,写起来不优雅不简洁,如果嵌套很多的话也会发生“嵌套地狱”。但是,如果用箭头函数的话,用1行代码就搞定了。
const add = (a) => (b) => a + b;
其它
另外,我们在看类似react-redux的connect代码的时候有时会有点懵:
const VisibleTodoList = connect(
mapStateToProps,
mapDispatchToProps
)(TodoList)
这什么写法?实际上就是柯里化而已,只不过对connect做了箭头函数的两重嵌套而已!!!