Bind创建一个新函数,该函数将强制函数中的this
作为传递给bind()
的参数.
下面的示例演示了如何使用bind
传递具有正确this
的成员方法:
var myButton = {
content: 'OK',
click() {
console.log(this.content + ' clicked');
}
};
myButton.click();
var looseClick = myButton.click;
looseClick(); // not bound, 'this' is not myButton - it is the globalThis
var boundClick = myButton.click.bind(myButton);
boundClick(); // bound, 'this' is myButton
打印出:
OK clicked
undefined clicked
OK clicked
您还可以在第一个(this
)参数之后添加额外的参数,bind
会将这些值传递给原始函数.稍后传递给绑定函数的任何附加参数都将在绑定参数之后传入:
// Example showing binding some parameters
var sum = function(a, b) {
return a + b;
};
var add5 = sum.bind(null, 5);
console.log(add5(10));
打印出:
15
查看JavaScript Function bind了解更多信息和互动示例.
更新:ECMAScript 2015增加了对=>
个函数的支持.=>
函数更紧凑,并且不会从定义范围更改this
指针,因此您可能不需要经常使用bind()
.例如,如果您希望第一个示例中的Button
上的函数将click
回调连接到DOM事件,那么以下都是有效的方法:
var myButton = {
... // As above
hookEvent(element) {
// Use bind() to ensure 'this' is the 'this' inside click()
element.addEventListener('click', this.click.bind(this));
}
};
或者:
var myButton = {
... // As above
hookEvent(element) {
// Use a new variable for 'this' since 'this' inside the function
// will not be the 'this' inside hookEvent()
var me = this;
element.addEventListener('click', function() { me.click() });
}
};
或者:
var myButton = {
... // As above
hookEvent(element) {
// => functions do not change 'this', so you can use it directly
element.addEventListener('click', () => this.click());
}
};