bind() 函数会建立一个新函数(称为绑定函数),新函数与被调函数(绑定函数的目标函数)具备相同的函数体(在 ECMAScript 5 规范中内置的call属性)。当新函数被调用时 this 值绑定到 bind() 的第一个参数,该参数不能被重写。绑定函数被调用时,bind() 也接受预设的参数提供给原函数。一个绑定函数也能使用new操做符建立对象:这种行为就像把原函数当成构造器。提供的 this 值被忽略,同时调用时的参数被提供给模拟函数。javascript
当建立一个对象时,调用对象里的方法,那么this值即为这个对象。当把这个方法赋值给某个变量后,经过这个变量调用方法,this值则会指向这个变量所在的对象。java
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参数后面,这句话不太好理解,仍是直接看代码吧。dom
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
的用法介绍到这里就结束了,更多资料请参考 MDNthis