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。

  • 相关阅读:
    配置VSFTP文件服务器
    Apache Tomcat服务部署网站
    NFS实现Unix-like文件共享
    OpenSSH 服务配置与管理
    Redis 数据库配置与应用
    Rsync+Inotify 实现数据同步
    PXE+Kickstart 自动化部署系统
    PostFix+Dovecot 部署邮件系统
    部署MooseFS分布式文件系统
    MVC5+EF6 完整教程
  • 原文地址:https://www.cnblogs.com/hcy1996/p/5947716.html
Copyright © 2011-2022 走看看