prototype.js中Function.prototype.bind方法浅解

prototype.js中的Function.prototype.bind方法:

Function.prototype.bind = function() {
    var __method = this;
    var args = Array.prototype.slice.call(arguments);
    var object=args.shift();
    return function() {
        return __method.apply(object,
             args.concat(Array.prototype.slice.call(arguments)));
    }
}

为所有function对象增加一个新的prototype(原型)方法bind:

  • 将调用bind方法的对象保存到__method(方法)变量里面。
  • 将调用bind方法时传递的参数转换成为数组保存到变量args。
  • 将args数组的第一位[0]元素提取出来保存到变量object。
  • 返回一个函数。

这个被返回的函数在再次被调用的时候执行如下操作:

  • 使用apply方法将调用bind方法的函数里面的this指针替换为object。
  • 将传递到这个匿名函数里面的参数转换为数组,与args数组组合形成一个新的数组,传递给__method方法。

例子:

function o(){
    this.num = 1;
    var fn = function(arg){alert(this.num+arg)}.bind(this,2);
    fn(); //alert(3)
}
new o()
原文地址:https://www.cnblogs.com/weekend001/p/3801303.html