bind()在 JavaScript 中有什么用?
bind()
Bind 创建一个新函数,它将强制this函数内部成为传递给的参数bind()。
this
这是一个示例,展示了如何使用bind传递具有正确的成员方法this:
bind
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 函数绑定以获取更多信息和交互式示例。
更新:ECMAScript 2015 增加了对=>函数的支持。 =>函数更紧凑,并且不会this从其定义范围更改指针,因此您可能不需要bind()经常使用。例如,如果您希望Button第一个示例中的函数将click回调连接到 DOM 事件,则以下都是有效的方法:
=>
Button
click
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()); } };