定义:
bind()
方法创建一个新的函数,在 bind()
被调用时,这个新函数的 this
被指定为 bind()
的第一个参数,而其余参数将作为新函数的参数,供调用时使用。
用法:
bind()
最简单的用法是创建一个函数,不论怎么调用,这个函数都有同样的 this
值。
<script> var name='hhh'; function demo(){ console.log('demo.name',this.name); } var a={ name:"linjianbin", } var demo2= demo.bind(a); demo();///hhh demo2();//linjianbin </script>
2.bind()
的另一个最简单的用法是使一个函数拥有预设的初始参数。只要将这些参数(如果有的话)作为 bind()
的参数写在 this
后面。当绑定函数被调用时,这些参数会被插入到目标函数的参数列表的开始位置,传递给绑定函数的参数会跟在它们后面。、
var demo= function(){ return arguments; } var demo2=demo.bind(demo,23); console.log(demo2(1,2,3,4,5));//23,1,2,3,4,5
3.在默认情况下,使用 window.setTimeout()
时,this
关键字会指向 window
(或 global
)对象。当类的方法中需要 this
指向类的实例时,你可能需要显式地把 this
绑定到回调函数,就不会丢失该实例的引用。
<script> function LateBloomer() { this.petalCount = 10 + 1; } // 在 1 秒钟后声明 bloom 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(); // 一秒钟后, 调用 'declare' 方法 </script>