bind()
有什么用在 JavaScript 中?
最佳答案
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/