0%

函数柯里化

函数柯里化就是只传递给函数一部分参数来调用它,让它返回一个函数去处理剩下的参数

1
2
3
4
5
6
7
8
9
10
11
12
function add(x, y) {
return x+y
}

function curryingAdd(x) {
return function (y) {
return x + y
}
}

console.log(add(1, 2)) //3
console.log(curryingAdd(1)(2)) //3

函数柯里化的好处

1、参数复用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function check(reg, txt) {
return reg.test(txt)
}

console.log(check(/\d+/g, 'test'))
console.log(check(/[a-z]+/g, 'test'))

//使用柯里化之后
function curryingCheck(reg) {
return function (text) {
return reg.test(text)
}
}

let hasNumber = curryingCheck(/\d+/g)
let hasString = curryingCheck(/[a-z]+/g)

console.log(hasNumber('783927382'))
console.log(hasString('test1'))

如上面的例子,使用柯里化函数之后,先将正则表达式作为第一个参数传进去作为模板,后面可以利用这个模板传入要检测的字符,从而实现多次调用。

2、延迟运行

bind函数的实现,bind绑定this的时候是不会自动执行的,需要手动执行。

1
2
3
4
5
6
7
Function.prototype.bind = function (context) {
var _this = this
var args = Array.prototype.slice.call(arguments, 1) //将类数组变成数组,并返回arguments中除了第一个参数的剩余参数,因为第一个参数是绑定的上下文
return function() {
return _ this.apply(context, args)
}
}