javascript中的bind应该怎么用?

bind() 函数会创建一个新函数(称为绑定函数),新函数与被调函数(绑定函数的目标函数)具有相同的函数体(在 ECMAScript 5 规范中内置的call属性)。当新函数被调用时 this 值绑定到 bind() 的第一个参数,该参数不能被重写。绑定函数被调用时,bind() 也接受预设的参数提供给原函数。一个绑定函数也能使用new操作符创建对象:这种行为就像把原函数当成构造器。提供的 this 值被忽略,同时调用时的参数被提供给模拟函数。

绑定函数

当创建一个对象时,调用对象里的方法,那么this值即为这个对象。当把这个方法赋值给某个变量后,通过这个变量调用方法,this值则会指向这个变量所在的对象。

this.x=9;
var module={
  x:1,
  getX:function(){
    console.log(this.x);
  }
}

module.getX();  //输出 1

var retrieveX=module.getX;
retrieveX();    //输出9

var boundGetX = retrieveX.bind(module);
boundGetX();    //输出1

偏函数

绑定函数拥有预设的初始值,初始参数作为bind函数的第二个参数跟在this对象后面,调用bind函数传入的其他参数,会跟在bind参数后面,这句话不太好理解,还是直接看代码吧。

var list=function(){
  var args= Array.prototype.slice.call(arguments);
  console.log(args);
  return args
};

var boundList=list.bind(undefined,37);
boundList();   //[3,7]
boundList(2,3,4); 

配合setTimeout或者setInterval

当使用setTimeout或者setInterval的时候,回调方法中的this值会指向window对象。我们可以通过显式的方式,绑定this值。

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

LateBloomer.prototype.bloom = function() {
  window.setTimeout(this.declare.bind(this), 1000);
};

LateBloomer.prototype.declare = function() {
  console.log('I am a beautiful flower with ' +
    this.petalCount + ' petals!');
};

var flower = new LateBloomer();
flower.bloom(); 

bind的用法介绍到这里就结束了,更多资料请参考 MDN

猜你喜欢

转载自www.cnblogs.com/fallsank/p/9391580.html
今日推荐