I have searched and read about this question for so long and yet still cannot wrap my head around. So in a React class component, you would write methods like this:
class Test extends React.Component {
constructor(props){
super(props)
this.method = this.method.bind(this)
}
method() {
...
}
}
If "this" is not bound by default, why can we use "this.method"? What does "this" mean in "this.method" and "bind.(this)". Are they the same?
This line: this.method = this.method.bind(this) really confuses me. Please help me explain each one of 3 "this" in this line. Thanks.
Binding a method to "this" is useful when you pass it to a child component. When you do this, it is usually to be able to change the local state of the parent component when the child component executes this method. It's kind of like saying
"I want this method to be bound to this class, that is, if it's called from anywhere, the references to "this" inside this method refer to THIS class"
Here is an interesting article that explains this in detail:
https://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/