概念
只传递给函数一部分参数调用它,返回一个函数去处理剩下的参数
优点
- 参数复用
function add (a) {
return function (b) {
return function (c) {
return a + b + c
}
}
}
let add1 = add(1)
console.log(add1(2)(3)) // 6
console.log(add1(4)(5)) // 10
let add2 = add1(2)
console.log(add2(4)) // 7
console.log(add2(5)) // 8`
add1就是复用参数:1,而add2则复用了参数:1和2两个参数
- 提前返回
var addEvent = (function () {
if (window.addEventListener) {
return function (el, type, fn, capture) {
el.addEventListener(type, function (e) {
fn.call(el, e)
})
}
} else if (window.attachEvent) {
return function (el, type, fn, capturn) {
el.attachEvent(type, function(e) {
fn.call(el, e)
})
}
}
})()
addEvent(document.getElementByTagName('div'), 'click', function(){}, true)
addEvent('div', 'click', function () {}, false)
addEvent('p', 'click', function () {}, false)
addEvent('div', 'dblclick', function () {}, false)
对于监听事件的判断则只会走一次,如果是传统函数则会多次执行。这是提前返回的好处。
- 延迟计算/运行
let allScore = 0
let curry = function (fn) {
let allParam = []
return function () {
if (arguments.length === 0) {
fn.call(null, allParam)
} else {
allParam = allParam.concat([].slice.call(arguments))
}
}
}
var currentCurry = curry(function(allParam){
for (let i = 0; i < allParam.length; i++) {
allScore += allParam[i]
}
})
curryAddScore(2)
curryAddScore(3)
curryAddScore(1)
console.log(allScore) // 0
curryAddScore(3)
curryAddScore()
console.log(allScore) // 9