zoukankan      html  css  js  c++  java
  • 柯里化、软绑定

    var currying = function(fn){
                    
                    var Args = [].slice.call(arguments, 1);  //此时Args = ['aaa'];
                    
                    return function(/*get调用时传入的参数*/){
                        //此时arguments = ['bbb','ccc','ddd','eee']; newArgs = ['aaa','bbb','ccc','ddd','eee'];
                        var newArgs = Args.concat([].slice.call(arguments));  
                        
                        return fn.apply(null, newArgs);
                    }
                };
                                                     
                var get = currying(function(){ 
                    //这里的allArgs = newArgs;
                    var allArgs = [].slice.call(arguments); 
                    
                    console.log(allArgs.join(';')); 
                }, 'aaa');
                
                get('bbb','ccc','ddd','eee')   //[aaa;bbb;ccc;ddd;eee]

    主要是受到《你不知道的JavaScript(上卷)》中,软绑定softBind()方法启发,当中应用了柯里化,这种方式确实刚开始不好理解,观看了张鑫旭的博客后,才对柯里化的方式有了一点了解。

    软绑定代码,如下:

    if( !Function.prototype.softBind ){
                    Function.prototype.softBind = function(obj){
                        var fn = this;
                        
                        var curried = [].slice.call(arguments, 1);
                        var bound = function(){
                            return fn.apply(
                                ( !this || this ===(window || global) ) ? obj : this,
                                curried.concat.apply( curried , arguments )
                            );
                        };
                        bound.prototype = Object.create( fn.prototype );
                        return bound;
                    };
                }

    软绑定优化了硬绑定,使this指向更加灵活,可以使用隐式绑定或者显式绑定修改this。

  • 相关阅读:
    IBM Minus One(water)
    约瑟夫问题的循环链表实现
    双向链表(差不多)
    单向链表的建立,插入,删除(复习一下)
    找新朋友(欧拉函数)
    验证角谷猜想(hd1279)
    Wolf and Rabbit(gcd)
    Big Number(大数)
    字串数(高精度组合数)
    寻找素数对(hd1262)
  • 原文地址:https://www.cnblogs.com/hcy1996/p/5947716.html
Copyright © 2011-2022 走看看