js柯里化

来源:互联网 发布:期货决策软件 编辑:程序博客网 时间:2024/05/17 17:44

柯里化允许我们把函数与传递给它的参数相结合,产生一个新的函数。最大的作用是参数复用。

//给所有函数都添加一个method方法,用于添加其他方法//原型链是F->Function.prototype->Object.prototypeFunction.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=2console.log(add2(3));//6