Javascript中bind()方法的使用与实现

在讨论bind()方法以前咱们先来看一道题目:javascript

javascriptvar altwrite = document.write;
altwrite("hello");
//1.以上代码有什么问题
//2.正确操做是怎样的
//3.bind()方法怎么实现

对于上面这道题目,答案并非太难,主要考点就是this指向的问题,altwrite()函数改变this的指向global或window对象,致使执行时提示非法调用异常,正确的方案就是使用bind()方法:java

javascriptaltwrite.bind(document)("hello")

固然也可使用call()方法:web

javascriptaltwrite.call(document, "hello")

本文的重点在于讨论第三个问题bind()方法的实现,在开始讨论bind()的实现以前,咱们先来看看bind()方法的使用:数组

绑定函数

bind()最简单的用法是建立一个函数,使这个函数不论怎么调用都有一样的this值。常见的错误就像上面的例子同样,将方法从对象中拿出来,而后调用,而且但愿this指向原来的对象。若是不作特殊处理,通常会丢失原来的对象。使用bind()方法可以很漂亮的解决这个问题:浏览器

javascriptthis.num = 9; 
var mymodule = {
  num: 81,
  getNum: function() { return this.num; }
};

module.getNum(); // 81

var getNum = module.getNum;
getNum(); // 9, 由于在这个例子中,"this"指向全局对象

// 建立一个'this'绑定到module的函数
var boundGetNum = getNum.bind(module);
boundGetNum(); // 81

偏函数(Partial Functions)

Partial Functions也叫Partial Applications,这里截取一段关于偏函数的定义:app

Partial application can be described as taking a function that accepts some number of arguments, binding values to one or more of those arguments, and returning a new function that only accepts the remaining, un-bound arguments.dom

这是一个很好的特性,使用bind()咱们设定函数的预约义参数,而后调用的时候传入其余参数便可:函数

javascriptfunction list() {
  return Array.prototype.slice.call(arguments);
}

var list1 = list(1, 2, 3); // [1, 2, 3]

// 预约义参数37
var leadingThirtysevenList = list.bind(undefined, 37);

var list2 = leadingThirtysevenList(); // [37]
var list3 = leadingThirtysevenList(1, 2, 3); // [37, 1, 2, 3]

和setTimeout一块儿使用

通常状况下setTimeout()的this指向window或global对象。当使用类的方法时须要this指向类实例,就可使用bind()将this绑定到回调函数来管理实例。this

javascriptfunction Bloomer() {
  this.petalCount = Math.ceil(Math.random() * 12) + 1;
}

// 1秒后调用declare函数
Bloomer.prototype.bloom = function() {
  window.setTimeout(this.declare.bind(this), 1000);
};

Bloomer.prototype.declare = function() {
  console.log('我有 ' + this.petalCount + ' 朵花瓣!');
};

注意:对于事件处理函数和setInterval方法也可使用上面的方法prototype

绑定函数做为构造函数

绑定函数也适用于使用new操做符来构造目标函数的实例。当使用绑定函数来构造实例,注意:this会被忽略,可是传入的参数仍然可用。

javascriptfunction Point(x, y) {
  this.x = x;
  this.y = y;
}

Point.prototype.toString = function() { 
  return this.x + ',' + this.y; 
};

var p = new Point(1, 2);
p.toString(); // '1,2'


var emptyObj = {};
var YAxisPoint = Point.bind(emptyObj, 0/*x*/);
// 实现中的例子不支持,
// 原生bind支持:
var YAxisPoint = Point.bind(null, 0/*x*/);

var axisPoint = new YAxisPoint(5);
axisPoint.toString(); // '0,5'

axisPoint instanceof Point; // true
axisPoint instanceof YAxisPoint; // true
new Point(17, 42) instanceof YAxisPoint; // true

上面例子中Point和YAxisPoint共享原型,所以使用instanceof运算符判断时为true。

捷径

bind()也能够为须要特定this值的函数创造捷径。

例如要将一个类数组对象转换为真正的数组,可能的例子以下:

javascriptvar slice = Array.prototype.slice;

// ...

slice.call(arguments);

若是使用bind()的话,状况变得更简单:

javascriptvar unboundSlice = Array.prototype.slice;
var slice = Function.prototype.call.bind(unboundSlice);

// ...

slice(arguments);

实现

上面的几个小节能够看出bind()有不少的使用场景,可是bind()函数是在 ECMA-262 第五版才被加入;它可能没法在全部浏览器上运行。这就须要咱们本身实现bind()函数了。

首先咱们能够经过给目标函数指定做用域来简单实现bind()方法:

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

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

javascriptFunction.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()方法能够绑定对象,也支持在绑定的时候传参。

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

javascriptFunction.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()实现。

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

javascriptFunction.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;
  };

欢迎光临小弟博客:Superlin's Blog
个人博客原文:Javascript中bind()方法的使用与实现

相关文章
相关标签/搜索