''this'' in stand alone function

When the render function is called, it has the correct this. So when it calls this.getBadgeColor() and this.formatCount(), those functions also have the correct this and everything works as expected. But notice that the render function isn’t calling this.handleIncrement, if it were you would see parentheses like this.handleIncrement(). Rather, it’s passing the handleIncrement function over to the onClick event to be called later. When you pass functions around, the this doesn’t automatically go along with the function, unless you do something to bind it to the function. For example in the constructor you could

this.handleIncrement = this.handleIncrement.bind(this);

which creates a new version of the handleIncrement function that always has the correct this.

More details here.

1 Like