使用JavaScript'bind'方法 [英] Use of the JavaScript 'bind' method

查看:188
本文介绍了使用JavaScript'bind'方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaScript中 bind()有什么用?

What is the use of bind() in JavaScript?

推荐答案

Bind创建一个新函数,将设置为传递给 bind()的第一个参数。

Bind creates a new function that will have this set to the first 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 Button = function(content) { 
  this.content = content;
};
Button.prototype.click = function() {
  console.log(this.content + ' clicked');
};

var myButton = new Button('OK');
myButton.click();

var looseClick = myButton.click;
looseClick(); // not bound, 'this' is not myButton - it is the global object

var boundClick = myButton.click.bind(myButton);
boundClick(); // bound, 'this' is myButton

打印出来:

OK clicked
undefined clicked
OK clicked

您还可以在第一个()参数和 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增加了对 => 的功能。 => 函数更紧凑,不会从定义范围更改指针,因此您可能不需要经常使用 bind()。例如,如果您想要第一个示例中的 Button 上的函数来挂接,请单击回调到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:

Button.prototype.hookEvent(element) {
  // Use bind() to ensure 'this' is the 'this' inside click()
  element.addEventListener('click', this.click.bind(this));
};

或者:

Button.prototype.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() });
}

或:

Button.prototype.hookEvent(element) {
  // => functions do not change 'this', so you can use it directly
  element.addEventListener('click', () => this.click());
}

这篇关于使用JavaScript'bind'方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆