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。

  • 相关阅读:
    WLAN设备接入过程
    802.1帧格式、帧类型详解
    SSID、BSSID、BSS等区分
    802.11协议详解
    bit、Byte、Mbps、Mb/s区别
    WLAN认证技术
    freemarker的简单使用案例
    关于throw、throws、try--catch的问题
    String去重方法
    常用典型的sql语句
  • 原文地址:https://www.cnblogs.com/hcy1996/p/5947716.html
Copyright © 2011-2022 走看看