在ReactJS中实际上是在做什么bind(this)?

时间:2018-08-24 06:54:26

标签: reactjs react-state-management

this.something = this.something.bind(this)

以上一行实际上在做什么?我是新手,因此也请以技术性的方式对我进行基本的解释(以我的理解)

1 个答案:

答案 0 :(得分:0)

以上一行实际上在做什么?

Use of the JavaScript 'bind' method

  

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

这是必需的,因为在DOM库和JavaScript的许多部分中,隐藏/隐式this函数参数已更改为指向幕后的不同对象。

一个很好的示例涉及JavaScript中的事件处理程序,其中this参数不是看起来的样子:

HTML:

<button id="someButton" name="Bar">Hello</button>

JavaScript(在加载DOM后运行):

function Foo() {
    this.name = "Foo";
}
Foo.prototype.eventHandler( event ) {
    console.log( event.type ); // will always print "click"
    console.log( this.name ); // will print either "Foo" or "Bar"
}

var button = document.getElementById("someButton"); // HTMLButton

var fooInstance = new Foo(); // fooInstance.name == "Foo"

button.addEventListener( 'click', fooInstance.eventHandler );

如果运行此代码并单击按钮并在Foo.prototype.eventHandler中设置断点,则您会看到this.name"Bar"而不是"Foo"-即使您传递了对fooInstance.eventHandler的引用,该引用在调用时肯定知道fooInstance

不是。

这是因为DOM API将this中的fooInstance.eventHandler更改为button实例。我不知道确切的原因,但我相信这与保持与老式的基于HTML属性的基于JavaScript的事件处理程序的向后兼容性有关,例如:

<button onclick="alert(this.name)" name="Baz">Click me</button>

this指的是包含的HTMLElement

因此,使用.bind 覆盖库的更改为this。您可能会认为,.bind(this)返回另一个Function时,this参数仍然会更改,但实际上不会更改。这是因为与大多数Function对象不同,返回的this实际上根本不能更改其Function成员。

在ReactJS中:

使用foo = foo.bind(this)并不是ReactJS的唯一功能(它是JavaScript的一部分),但它是ReactJS中的一个习惯用法:

why do you need to bind a function in a constructor

  

这是因为React不想弄乱ES6规范(将其绑定到其类中的功能不在ES6类规范中),但是同时希望为其用户提供ES6类语法的便利。您可以在下面阅读有关此内容的更多信息。