关于箭头函数嵌套,也称为函数柯里化,它只不过是箭头函数的语法糖。那在项目中一般怎么使用呢?
(1)普通函数:
function add(a, b) {
return a + b;
}
(2)普通函数柯里化(匿名函数)
function add(a) {
return function(b) {
return a + b;
}
}
调用 console.log(add(4)(5)); //输出9
上面那段柯里化的代码很难懂啊,而且有嵌套,写起来不优雅不简洁,如果嵌套很多的话也会发生“嵌套地狱”。但是,如果用箭头函数的话,用1行代码就搞定了。
(3)箭头函数柯里化
const add = (a) => (b) => a + b;
调用 console.log(add(4)(5)); //输出9
(4) react中的使用
类似react-redux的connect代码
const VisibleTodoList = connect(
mapStateToProps,
mapDispatchToProps
)(TodoList)
(5)原始 ES5和ES6的多重嵌套函数对比(具名的函数)
ES5的代码
function insert(value) {
return {
into: function(array) {
return {
after: function(afterValue) {
array.splice(array.indexOf(afterValue) + 1, 0, value);
return array
}
}
}
}
}
console.log(insert(1).into([1, 3]).after(1)); //[1, 1, 3]
console.log(insert(5).into([1, 3]).after(3)); //[1, 3, 5]
ES6箭头函数
let insert = (value) => ({
into: (array) => ({
after: (afterValue) => {
array.splice(array.indexOf(afterValue) + 1, 0, value);
return array
}
})
})
console.log(insert(1).into([1, 3]).after(1)); //[1, 1, 3]
console.log(insert(5).into([1, 3]).after(3)); //[1, 3, 5]