First of all, it must be said that the point of this cannot be determined when the function is defined, only when the function is executed can it be determined who this points to, in fact, the final point of this is the object that calls it (there are some problems with this sentence, and it will be explained later why there is a problem, although most of the articles on the Internet say this, although in many cases there will be no problem with that understanding, but in fact that understanding is inaccurate, So when you understand this, you will have a feeling of incomprehension), so I will explore this issue in depth.
The test is as follows:
This has different values for different purposes of functions. In general, this is the environment object in which the function runs. The usage of this is discussed in detail in four situations.
Case 1: Pure function calls
This is the most common use of a function, and it is a global call, so this represents a global object. Look at the code below, it runs with a result of 1.
Case 2: Call as an object method
The function can also be called as a method of an object, in which case this refers to the parent object.
Case 3 Call as a constructor
The so-called constructor is through this function, a new object can be generated. At this point, this refers to this new object.
The result of the run is 1. To show that this is not a global object at this time, we make some changes to the code:
The result of the run is 2, indicating that the value of the global variable x has not changed at all.
Case 4 apply call
apply() is a method of a function that changes the calling object of the function. Its first parameter represents the changed object that calls the function. Therefore, this refers to this first parameter.
When the apply() parameter is empty, the global object is called by default. Therefore, the result of the run is 0, proving that this refers to the global object.
If you change the last line of code to
The running result becomes 1, proving that this represents the object obj.
(End)
Reference:
The hyperlink login is visible.
The hyperlink login is visible.
|