函数柯里化的理解

// 实现一个add方法,使计算结果能够满足如下预期:
            // add(1)(2)(3) = 6;
            // add(1, 2, 3)= 6;
            // add(1)(2,3)= 6;
            function add(){
                var _args = Array.prototype.slice.apply(arguments)
                // 每次_add传入的参数都保存到_args中
                // 这里体现了 柯里化 参数复用 (_args)与 延迟执行(等到所有参数收集完毕再进行计算)的两大特点
                var _add = function(){
                    Array.prototype.slice.apply(arguments).forEach(function(item){
                        // 另一个特性,在最终结算结果之前提前确认参数,
                        if(!isNaN(item)){
                            _args.push(item)
                        }
                    })
                    return _add
                }
                // 利用toString隐式转换的特性,当最后执行时隐式转换,并计算最终的值返回
                _add.toString = function(){
                    return _args.reduce(function(x,y){
                        return x + y
                    })
                }
                return _add;
            }
            //总结柯里化三大特性: 1,参数复用;2,延迟执行;3,提前确认
            console.log('this.add(1,2,3)='+this.add(1,2,3)) //6
            console.log('this.add(1,2)(3)='+this.add(1,2)(3)) //6
            console.log('this.add(1)(2)(3)='+this.add(1)(2)(3)) //6
            console.log('this.add(1)(2,3)='+this.add(1)(2,3))//6
            console.log('this.add(1)(2,3)(4)='+this.add(1)(2,3)(4))//10
            console.log("this.add(1)(2,'a')(4)="+this.add(1)(2,'a')(4))//7

猜你喜欢

转载自www.cnblogs.com/weiziyu/p/12604578.html