JavaScript高阶函数之uncurrying和currying

uncurrying函数是实现从别的对象中赋值方法,如下功能:将Array中的push方法赋值出来,单独使用。

        //实现方式一:
        Function.prototype.uncurrying= function () {
            var __self = this;
            return function () {
                var obj = Array.prototype.shift.call(arguments);
                return __self.apply(obj,arguments);
            };
        };
 //实现方式二:
        Function.prototype.uncurrying = function(){
            var self = this;
            return function(){
                return Function.prototype.call.apply( self, arguments );
            };
        };


        var push = Array.prototype.push.uncurrying();

        (function(){

            push(arguments,4);

            console.log(arguments);

        })(1,2,3);
        //  (4) [1, 2, 3, 4, callee: function, Symbol(Symbol.iterator): function]
Function.prototype.uncurrying = function () {
            var self = this;//保存原函数
            return function () {
                return Function.prototype.call.apply(self,arguments);
            };
        };
        var push = Array.prototype.push.uncurrying();
        var obj = {
            "length": 1,
            "0": 1 
        };
        push(obj,2);
        push(obj,3);
        console.log(obj);
//        Object  0: 1 , 1: 2  ,2:3, length: 3    __proto__: Object

柯里化(currying):arguments 的主要用途是保存函数参数, 但这个对象还有一个名叫 callee 的属性,该属性是一个指针,指向拥有这个 arguments 对象的函数。

 var currying = function (fn) {
            var args = [];
            return function () {
                if(arguments.length===0){
                    return fn.apply(this,args);
                }else{
                    [].push.apply(args,arguments);
                    return arguments.callee;//指向的是当前的闭包函数
                }
            }
        };

        var cost = (function () {
            var money = 0;
            return function () {
                for(var i = 0,l = arguments.length;i < l;i++){
                    money += arguments[i];
                }
                return money;
            }
        })();

        cost = currying(cost);

        console.log(cost(100));
        //function(){if(arguments.length===0){return fn.apply(this,args);}else{[].push.apply(args,arguments);return arguments.callee;}}
        console.log(cost(200));
        console.log(cost(400));
        alert(cost());
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值