JavaScript 中的 bind()
有什么用?
最佳答案
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
会将这些值传递给原始函数。您稍后传递给绑定(bind)函数的任何其他参数都将在绑定(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());
}
};
关于javascript - JavaScript 'bind' 方法有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29343412/