zoukankan      html  css  js  c++  java
  • javascript中利用柯里化函数实现bind方法

    • 柯理化函数思想:一个js预先处理的思想;利用函数执行可以形成一个不销毁的作用域的原理,把需要预先处理的内容都储存在这个不销毁的作用域中,并且返回一个小函数,以后我们执行的都是小函数,在小函数中把之前预先存储的值进行相关的操作处理即可;
    • 柯里化函数主要起到预处理的作用;
    • bind方法的作用:把传递进来的callback回调方法中的this预先处理为上下文context;
    /**
    * bind方法实现原理1
    * @param callback [Function] 回调函数
    * @param context [Object] 上下文
    * @returns {Function} 改变this指向的函数
    */
    function bind(callback,context) {
        var outerArg = Array.prototype.slice.call(arguments,2);// 表示取当前作用域中传的参数中除了fn,context以外后面的参数;
        return function (){
            var innerArg = Array.prototype.slice.call(arguments,0);//表示取当前作用域中所有的arguments参数;
            callback.apply(context,outerArg.concat(innerArg));
        }
    }
     
    /**
    * 模仿在原型链上的bind实现原理(柯理化函数思想)
    * @param context [Object] 上下文
    * @returns {Function} 改变this指向的函数
    */
    Function.prototype.mybind = function mybind (context) {
        var _this = this;
        var outArg = Array.prototype.slice.call(arguments,1);
        // 兼容情况下
        if('bind' in Function.prototype) {
            return this.bind.apply(this,[context].concat(outArg));
        }
        // 不兼容情况下
        return function () {
            var inArg = Array.prototype.slice.call(arguments,0);
            inArg.length === 0?inArg[inArg.length]=window.event:null;
            var arg = outArg.concat(inArg);
            _this.apply(context,arg);
        }
    }
  • 相关阅读:
    [python]百度语音rest api
    [vim]插件ctrlp
    [vim]插件NerdTree
    [Flask Security]当不能通过认证的时候制定跳转
    MongoDB 安装
    c/c++封装成python包
    mysql的常用操作
    python基础知识的学习和理解
    docker系列之三:docker实际应用
    docker系列之二:构建docker容器
  • 原文地址:https://www.cnblogs.com/jocyci/p/5444606.html
Copyright © 2011-2022 走看看