bind()实现

bind()函数是在 ECMA-262 第五版才被加入;它可能没法在全部浏览器上运行。这就须要咱们本身实现bind()函数了浏览器

简单实现bind()方法:app

Function.prototype.bind = function(context){
  self = this;  //保存this,即调用bind方法的目标函数
  return function(){
      return self.apply(context,arguments);
  };
};

考虑到函数柯里化的状况,咱们能够构建一个更加健壮的bind()函数

Function.prototype.bind = function(context){
  var args = Array.prototype.slice.call(arguments, 1),
  self = this;
  return function(){
      var innerArgs = Array.prototype.slice.call(arguments);
      var finalArgs = args.concat(innerArgs);
      return self.apply(context,finalArgs);
  };
};

此次的bind()方法能够绑定对象,也支持在绑定的时候传参。this

 

继续,Javascript的函数还能够做为构造函数,那么绑定后的函数用这种方式调用时,状况就比较微妙了,须要涉及到原型链的传递:spa

Function.prototype.bind = function(context){
  var args = Array.prototype.slice(arguments, 1),
  F = function(){},
  self = this,
  bound = function(){
      var innerArgs = Array.prototype.slice.call(arguments);
      var finalArgs = args.concat(innerArgs);
      return self.apply((this instanceof F ? this : context), finalArgs);
  };

  F.prototype = self.prototype;
  bound.prototype = new F();
  retrun bound;
}

这是《JavaScript Web Application》一书中对bind()的实现:经过设置一个中转构造函数F,使绑定后的函数与调用bind()的函数处于同一原型链上,用new操做符调用绑定后的函数,返回的对象也能正常使用instanceof,所以这是最严谨的bind()实现。prototype

对于为了在浏览器中能支持bind()函数,只须要对上述函数稍微修改便可:code

Function.prototype.bind = function (oThis) {
    if (typeof this !== "function") {
      throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
    }

    var aArgs = Array.prototype.slice.call(arguments, 1), 
        fToBind = this, 
        fNOP = function () {},
        fBound = function () {
          return fToBind.apply(
              this instanceof fNOP && oThis ? this : oThis || window,
              aArgs.concat(Array.prototype.slice.call(arguments))
          );
        };

    fNOP.prototype = this.prototype;
    fBound.prototype = new fNOP();

    return fBound;
  };
相关文章
相关标签/搜索