Get a deeper understanding of the `this` pointer in JavaScript

Tram Ho

In the process of learning and working with javascript the use of this is the easiest thing for js programmers to headache. So this what is it? This pointer is probably a not very unfamiliar concept in object oriented programming. If you have ever learned Java or C #, you must also remember that the this keyword refers to the object that calls the function. Here this it likewise also see the examples below to learn more about its basic offline.

Here this pointer is pointing to the correct object info to display the correct information you want. There is one other case we declare global variables in scope, the moment this will be pointing to the window where the object that contains the global variable.

So with the 2 above examples, we will think that this is generally easy to understand, but it is not difficult, right? But it’s not that the following things here are exactly what we need to be aware of.

1. Used in conjunction with callback function

For example we want to click on a button to show user information. We simply pass the showInfo () function as a callback to the click function.

However, when opening developer tools, this here is pointing to the button , not the info object as before. That will make the display of the data wrong. To fix this error we just need to use the bind or an anonymous function.

2. Use with anonymous function

Suppose there is a school object and you want to show all the classes in that school then we do the following.

Now we are using the forEach function and inside is an anonymous fucntion, this will point to the window object so nameSchool will now be undefined. To solve this we often use is to create a variable to assign this value, and access that value in an anonymous function.

3. Use when assigning a function to another variable

This case is very rare to encounter. That is the case when we assign a function to a variable, then call that function. The function will not run as expected, because the object calling the function is now the object window.

Similar to the cases analyzed above, the context of the info.showInfo function is changed when we assign the function to another specific object here this is being assigned to the object window. To keep the context as the info variable, we will edit the code as follows:

summary

Through this article you have also seen how this is a bit complicated already. Be careful using it from now on to avoid errors! Reference link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

Share the news now

Source : Viblo