''this'' in stand alone function

Hi guys,

Quite confuse about the this in the react. The code in the picture is from react course. Mosh said the ‘this’ in the "handleIncrement"function is undefined because it is a stand alone function. My question is function “getBadgeColor” and “formatCount” seem like stand alone function as well but why they can be called without any problem and don’t need the ‘bind’ method.

1 Like

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