JavaScript 'bind' 方法的用途是什么? [英] What is the use of the JavaScript 'bind' method?
问题描述
bind()
在 JavaScript 中有什么用?
What is the use of bind()
in JavaScript?
推荐答案
Bind 创建一个新函数,该函数将强制函数内的 this
成为传递给 bind()<的参数/代码>.
Bind creates a new function that will force the this
inside the function to be the parameter passed to bind()
.
下面是一个示例,展示了如何使用 bind
来传递具有正确 this
的成员方法:
Here's an example that shows how to use bind
to pass a member method around that has the correct 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
会将这些值传递给原始函数.您稍后传递给绑定函数的任何其他参数都将在绑定参数之后传入:
You can also add extra parameters after the 1st (this
) parameter and bind
will pass in those values to the original function. Any additional parameters you later pass to the bound function will be passed in after the bound parameters:
// 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 函数绑定以获取更多信息和交互式示例.
Check out JavaScript Function bind for more info and interactive examples.
更新:ECMAScript 2015 添加了对 =>
函数的支持.=>
函数更紧凑,并且不会从它们的定义范围更改 this
指针,因此您可能不需要使用 bind()
经常.例如,如果您希望第一个示例中 Button
上的函数将 click
回调连接到 DOM 事件,那么以下都是有效的方法:
Update: ECMAScript 2015 adds support for =>
functions. =>
functions are more compact and do not change the this
pointer from their defining scope, so you may not need to use bind()
as often. For example, if you wanted a function on Button
from the first example to hook up the click
callback to a DOM event, the following are all valid ways of doing that:
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 'bind' 方法的用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!