This object has always been a trap in js. It is difficult to judge what it points to, and we often make this type of mistake due to our experience with self from C or python. Next, let’s talk about the ownership of this object in detail.
rule1: this
of the global environmentThe environment of JavaScript is inherently determined by functions. In JS, context cannot be separated by code blocks. The environment that is not wrapped by functions is the global environment. This in the global environment points to the global variable window. See the following example.
rule2: this
when called as a methodObviously, this situation is easy to judge. It is consistent with self in python. This undoubtedly points to the object that calls the method
rule3: this
when used as a constructorNeedless to say, this at this time is obviously pointing to the newly created object. The running of the constructor does not actually create the object, but only initializes it. The object has been created before running
Here are some examples
rule4: this in indirect call
The so-called indirect call refers to using apply and call to call functions. At this time, this points to the first parameter in their parameter list.
rule5: this in other situations
Remember that this will not be changed in other cases, this is also where mistakes are most likely to occur.
The above code looks strange. Shouldn’t this point to person?
We should remember that this in the nested function will not point to the function in which it is nested. In this example, this in sayhello will not point to the function corresponding to hello. If we change the example slightly to become
Everyone should have understood that at this time, sayhello is not being called as a method, so this points to the global object. . .
At this time, the problem comes. When running the initial example using node, it will display undefined says hello world. I wonder if anyone can explain it.
rule6:eval breaks all rules
Finally end with an example
Do you understand?