How to use the value of ‘this’ inside the callback function?

Tram Ho

For those new to JavaScript, this is something very mysterious. And one of the common mistakes is to misuse this role within the callback function.
For example:

In the above code, the console displays NaN values ​​instead of 1 – as most newbie think. So how to use the value of this inside the callback function?

Basically this inside the JavaScript function

The keyword this inside the JavaScript function is a special keyword. The value of this determines based on how the function is called, not on where it is defined.
For example:

Or another example:

In the example above, increase is a function. So the value of this is determined based on how this function is called. Which increase is called in?
This is obj.increase (). Inferred, this here will correspond to obj. Therefore, the results obtained are as expected.

Some ways to properly use this value inside the callback function

Save the reference of this

The idea of ​​this method is that I will use any variable to store the value of this . Meanwhile, his concern this spring was bind with any guy.
Meanwhile, the code at the top of the article will change to:

Now, the value of self will correspond to this – corresponding to the Helper.

Use the bind method

The bind method will create a new function that when this function is called, the value of this will correspond to the value passed.

Apply bind to the above code, I will get:

The results are still exactly as expected.

Use the arrow function

The arrow function is different from the normal function as it doesn’t have this . Thus, the keyword this inside the arrow function will be treated as ordinary variables.

Now, the above code will change to:

Directly set the value of this

Some methods allow to directly set the value of this variable. For example, methods corresponding to Array: map (), forEach (), filter (), …
For example:

Inside the function , this value is undefined . Therefore, the result is an error Uncaught TypeError: Cannot read property ‘amount’ of undefined.
Now, I will pass the value of this into the forEach () method above to see how the result is.

Awesome! The results are completely accurate.


Above are some ways to use the correct value of this inside the callback function I have referenced based on a question on Stackoverflow, you can refer here How to access the correct ‘this’ inside a callback?
Good bye and see you again !

Share the news now

Source : Viblo