1. 程式人生 > >js柯里化

js柯里化

柯里化允許我們把函式與傳遞給它的引數相結合,產生一個新的函式。最大的作用是引數複用。

//給所有函式都新增一個method方法,用於新增其他方法
//原型鏈是F->Function.prototype->Object.prototype
Function.prototype.method = function(name,func){
    this.prototype[name]=func;
    return this;
}

//給所有函式新增一個curry方法
Function.method('curry',function(){
    var slice = [].slice;//arguments是類似陣列,但沒有任何陣列的方法,所以要將它轉為真正的陣列
var args = slice.call(arguments), that = this;//this指向呼叫它的函式 return function(){ return that.apply(null,args.concat(slice.call(arguments))); }; }) //測試,add函式 function add(a,b,c){ return a+b+c; } var add2 = add.curry(1,2);//複用引數a=1,b=2 console.log(add2(3));//6