js

js 级联函数与函数柯里化

Posted by czr on July 28, 2016

级联函数

用过jq的人估计都知道,jq有个链式堆,即可以

 $('.div').attr().html().remove();

其实里面就是级联函数的经典

举个栗子

我们声明一个人

    function person(){
            this.height='';
            this.age='';
            this.name='';
        }
        person.prototype={
                setname:function(){
                    this.name='rick';
                },
                setage:function(){
                    this.age='22';
                },
                setheight:function(){
                    this.height='178';
                }
        }
        var czr=new person();
        czr.setname();
        czr.setage();
        czr.setheight();
        console.log(czr)

能不能一次性设置完?改一下代码

        var czr=new person();
        czr.setname().setage().setheight();
        console.log(czr)

然而报错了,原理是这样的,czr.setname()后并没有把对象返回,而是设置了为undefind, 所以undefind.setage()就会报错了。怎么改呢?

    function person(){
            this.height='';
            this.age='';
            this.name='';
        }
        person.prototype={
                setname:function(){
                    this.name='rick';
                    return this
                },
                setage:function(){
                    this.age='22';
                    return this
                },
                setheight:function(){
                    this.height='178';
                }
        }
        var czr=new person();
        czr.setname();
        czr.setage();
        czr.setheight();
        console.log(czr)

成功了有木有

函数柯里化

    function add(){
            var total=0;
            for(i=0;i<arguments.length;i++){
                total+= arguments[i]

            }
            return total;
        }
        function curry(fn){
            var args=Array.prototype.slice.call(arguments,1);
            console.log(args)
            console.log(arguments)
            return function(){
                var innerarg=Array.prototype.slice.call(arguments);
                console.log(innerarg)
                var total=args.concat(innerarg);
                console.log(total)
                return fn.apply(this, total);
            }
        }
        console.log(curry(add)(1,2,5,9));

函数柯里化其实就是闭包的高级应用,主要有参数复用和提前返回两个特点,利用闭包缓存参数以及对参数进行复用,对多个参数进行分割调用,避免了函数嵌套


Creative Commons License
This work is licensed under a CC A-S 4.0 International License.