上面那行实际上在做什么?
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 将 fooInstance.eventHandler 的 this 更改为 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 规范(将 this 绑定到其类中的函数不在 ES6 类规范中),但同时又想给它的用户提供 ES6 类语法的便利.您可以在下面阅读更多相关信息。