currying 柯里化函数

我们平常写方法,比如写个加法

this.add(4, 5) //9
add(a,b){
    return a + b
}

使用 currying 后呢,我们可以写成这样

this.add(4)(5) //9
add(a){
  return (b)=>{
    return a + b
  }
}

这么看上去好像没有必要,但是有时候我们比如封装了一个方法,但是我们有其中一个参数是固定的,比如我们总要算 5+任意数

add(a){
  return (b) =>{
    return a + b
  }
}

let result = add(5)
console.log(result(6))      //11

TIP

注:这样就可以封装一些常用的方法,比如正则表达式这种,总要验证手机号啥的,就可以类似封装

TIP

这只是简单用法,详细用法可以参考一下 https://www.jianshu.com/p/2975c25e4d71open in new window