因此,我知道使用=>
函数可以帮助将方法与类进行静态绑定。
但是,我不明白的是相反的原因,为什么不使用bind
或=>
却不绑定在实例方法中。
以组件为例
import React from "react";
export default class ES6Class extends React.Component {
constructor(props) {
super(props);
}
renderDetails() {
console.log("With regular function, this refers to: ", this);
this.showAlert();
}
sayHi() {
alert("oh hi!");
}
render() {
console.log("this in render?", this);
return <button onClick={this.renderDetails}>Click me!</button>;
}
}
现在,当我运行此(https://codesandbox.io/embed/how-does-es6-classes-and-this-work-in-react-h4xm5)时,我得到以下信息
对于
console.log("this in render?", this);
我知道
this in render?
ES6Class {props: Object, context: Object, refs: Object, updater: Object, _reactInternalFiber: FiberNode…}
但是当我单击按钮时,我得到了
With regular function, this refers to: undefined
现在,我有以下问题,
<button onClick={this.renderDetails}>Click me!</button>;
this
中的this.renderDetails
是什么? My 'guess'?
是指ES6Class
,
为什么要猜?因为单击按钮后,它将执行功能renderDetails()
。如果我错了,请纠正我。
this
renderDetails() {
console.log("With regular function, this refers to: ", this);
this.showAlert();
}
当点击button
时
我超级困惑。我什至读过https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes,但听不懂。
如果可能,请帮助我理解并指出官方资源。该代码位于
https://codesandbox.io/embed/how-does-es6-classes-and-this-work-in-react-h4xm5
谢谢
更新1
感谢您的回答,我将继续摆弄它。接下来,我尝试了以下
let i = new ES6Class();
i.renderDetails();
let f = i.renderDetails;
f();
在这种情况下,我得到的是关注
With regular function, this refers to:
ES6Class {props: undefined, context: undefined, refs: Object, updater: Object, constructor: Object}
With regular function, this refers to: undefined
问题:为什么是undefined
而不是Global
或Window
?