javascript中利用柯里化函数实现bind方法

时间:2016-04-28 23:54:51   收藏:0   阅读:470
/**
* 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);
    }
}

 

原文:http://www.cnblogs.com/jocyci/p/5444606.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!