this.something = this.something.bind(this)
上面的行实际上在做什么?我是新手,所以请以技术的方式给出一个基本的解释(为了我的理解)
this.something = this.something.bind(this)
上面的行实际上在做什么?我是新手,所以请以技术的方式给出一个基本的解释(为了我的理解)
bind
创建一个新函数,将 this 设置为传递给的第一个参数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
of更改fooInstance.eventHandler
为button
实例。我不知道确切的原因,但我相信这与保持与老式基于 HTML 属性的 JavaScript 事件处理程序的向后兼容性有关,如下所示:
<button onclick="alert(this.name)" name="Baz">Click me</button>
(这里this
指的是包含HTMLElement
)
因此 using.bind
会覆盖库对this
. 您可能认为 as.bind(this)
返回另一个Function
参数this
无论如何都会更改,但实际上并没有。这是因为与大多数对象不同,Function
返回的对象实际上根本无法更改其成员。this
Function
的使用foo = foo.bind(this)
并不是 ReactJS 独有的(它是 JavaScript 的一部分),但它是 ReactJS 中的一个习惯用法:
这是因为 React 不想弄乱 ES6 规范(将 this 绑定到它的类中的函数不在 ES6 类规范中),但同时又想给它的用户提供 ES6 类语法的便利。您可以在下面阅读有关此内容的更多信息。