Talk about this in Javascript again, talk about javascriptthis
I have always had a similar feeling about this in Javascript. Today I suddenly feel very open, so I would like to record it.
Let's first look at a chestnut:
<! DOCTYPE html>
It seems that this code is correct, but the incorrect result is eventually caused by an incorrect understanding of this. We bound the click event on the element car_key, and thought that the dom element can access the car's this context by nesting the click event in the car class. This method looks reasonable, but unfortunately it doesn't work.
In Javascript, this keyword always points to the owner of the execution scope.
Please read the above sentence carefully. As we know, function calls will generate a new scope. When an onclick event is triggered, this points to the dom element rather than the Car class.
So how can we make it work? We usually assign this value to a local free variable (for example, that, _ this, self, me, etc., which is embodied in many frameworks) to avoid problems caused by the scope. Here we use local variables to override the previous method:
<! DOCTYPE html>
Because that is a free variable, The onclick event does not cause its redefinition.
If you are familiar with ES6, you can use the fat arrow symbol, which is more concise and easier to understand, as shown below:
<! DOCTYPE html>
Of course, we can also use the function binding method to solve this problem:
<! DOCTYPE html>
In fact, these pitfalls encountered when learning React and binding events. At that time, I only knew this and did not know what was going on. Today, I suddenly felt very open. Hope to help you.