There are already several questions on this topic, and I've looked at all I've found - my question is in order to clear up for myself some (apparent) contradictions that I'm seeing. I suspect there is a better solution than the only one I have working right now. I'm pretty new to Javascript.
I've read through the scoping rules on this
as described by e.g. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this . My understanding from reading is that although a lot depends on calling context, if a function is a method of an object then within the function this
will be the object itself. I thought this rule trumped the other rules, but perhaps I have misunderstood.
I've also read a post at https://medium.com/byte-sized-react/what-is-this-in-react-25c62c31480 which essentially says that if I want to access object state in a method via this
, and I have code like
class App extends Component {
constructor(props) {
super(props);
}
clickFunction() {
console.log(this.props.value);
}
render() {
return(
<div onClick={this.clickFunction}>Click Me!</div>
);
}
}
then I need to explicitly bind the object to clickFunction()
by either adding a line to the constructor like
this.clickFunction = this.clickFunction.bind(this);
or by using arrow notation to define clickFunction()
, like
const clickFunction = () => { ... }
The first of these solutions works for me - I have not got the second working. It seems strange to me that I need to use either solution since (a) it seems to contradict what I thought was the assertion in the docs that an object method will treat the object as this
, and (b) I don't see people doing this sort of thing in other tutorial examples that I look at.
For instance, there is a React tutorial at https://reactjs.org/tutorial/tutorial.html which defines object methods like renderSquare(i)
and does not at any point explicitly bind these methods to the object.
If I try to do something which seems to me completely analogous to that tutorial, and don't explicitly add lines to the constructor to bind each method to the object, i.e. lines like this.clickFunction = this.clickFunction.bind(this)
, then I can't get my code to work.
Can anyone explain to me what I am misunderstanding about the tutorial and the documentation - why does the tutorial work even though there is no explicit binding to the object? The only difference I can spot between it and my own code is that I have use strict
. Is there a better fix than the this.clickFunction.bind(this)
solution I'm currently using? Adding one extra line of code to the constructor per method, to explicitly bind all my methods, seems pretty clunky.