JavaScript函数柯里化1.定义:柯里化(Currying)是将一个接受多个参数的函数转化为一个接受单个参数(原函数的第一个参数)的函数,并返回一个函数的一种技术接受剩余参数并返回结果的新函数。让我用一个简单的例子来解释:functionadd(a,b){returna+b}add(1,2);//3将函数add转换为柯里化函数_add:function_add(a){returnfunction(b){returna+b}}_add(1)(2);//3functionadd和function_add是等价的。_add能够处理add的所有剩余参数,因此柯里化也称为部分求值。其实就是把add函数的a和b参数改成了一个接收a的函数,然后返回一个处理b参数的函数。现在思路应该比较清晰了:只传递一部分参数给函数调用,让它返回一个函数来处理剩下的参数。二、柯里化函数的作用1、参数复用案例:拼接地址按照通用思路拼接一个地址//拼接地址functiongetUrl(protocol,hostname,pathname){return`${protocol}${hostname}${pathname}`;}consturl1=getUrl('https://','www.baidu.com','/hasa');consturl2=getUrl('https://','www.知乎','/saandsa');consturl3=getUrl('https://','www.segmentfault.com','/hasak');console.log(url1,url2,url3)每次调用getUrl参数都要重复传入参数'https://'。curry封装后:functioncurry(protocol){returnfunction(hostname,pathname){return`${protocol}${hostname}${pathname}`;}}consturl_curry=curry('https://');consturl1=url_curry('www.baidu.com','/hasa');consturl2=url_curry('www.zhihu.com','/saandsa');consturl3=url_curry('www.segmentfault.com','/hasak');console.log(url1,url2,url3)显然经过柯里化和封装,后面拼接地址的时候,减少了参数个数,降低了代码重复率。2.提前确认/提前返回案例:兼容IE浏览器事件监听方式(IE已死)传统方式:/**@paramelementObjectDOM元素对象*@paramtypeString事件类型*@paramlistenerFunction事件处理函数*@paramuseCaptureBoolean是否捕获*/varaddEvent=function(element,type,listener,useCapture){if(window.addEventListener){element.addEventListener(type,function(e){listener.call(element,e)},useCapture)}else{element.attachEvent('on'+type,function(e){listener.call(element,e)})}}缺陷是每次绑定一个DOM元素时,都需要要重新判断,其实只要浏览器确认过事件监控网页,就可以知道浏览器需要哪种监控方式。所以我们可以让判断只执行一次。curry封装后:varaddEvent=(function(){if(window.addEventListener){returnfunction(element,type,listener,useCapture){//returnfunctionelement.addEventListener(type,function(){listener.call(element)},useCapture)}}else{returnfunction(element,type,listener){element.attachEvent('on'+type,function(){listener.call(element)})}}})()addEvent(element,"click",listener)立即执行函数,多个事件触发时只触发一次if条件判断。3、延时执行案例:钓鱼统计权重传统方法:letfishWeight=0;constaddWeight=function(weight){fishWeight+=weight;};addWeight(2.3);addWeight(6.5);addWeight(1.2);addWeight(2.5);console.log(fishWeight);每执行一次addWeight方法,就将鱼的重量累加一次。柯里化和打包后:functioncurryWeight(fn){let_fishWeight=[];返回函数(){if(arguments.length===0){returnfn.apply(null,_fishWeight);}else{_fishWeight=_fishWeight.concat([...arguments]);}}}functionaddWeight(){让fishWeight=0;for(leti=0,len=arguments.length;i
