The use of this in Javascript
Taken from: http://www.ruanyifeng.com/blog/2010/04/using_this_keyword_in_javascript.html This is a keyword in the Javascript language. It represents an internal object automatically generated during function runtime, which can only be used within the function itself. For example, the value of this in function test() {this. x=1;} will change depending on the usage of the function. But there is a general principle, which is that this refers to the object that calls the function. Below are four scenarios to discuss in detail the usage of this. Scenario 1: Pure function call. This is the most common usage of functions and belongs to global calls, so this represents the global object Global. Please take a look at the following code, its running result is 1. function test(){ this.x = 1; alert(this.x); } test(); //To prove that this is a global object, I made some changes to the code: var x=1; Function test() {alert (this. x);} test(); //The running result is still 1. Change again: var x=1; Function test() {this. x=0;} test(); Alert (x); //Scenario 2: The calling function as an object method can also be called as a method of a certain object, in which case this refers to the parent object. Function test() {alert (this. x);} var o={}; o. X=1; o. M=test; o. M(); //Scenario 3 calls the so-called constructor as a constructor, which generates a new object through this function. At this point, ‘this’ refers to this new object. Function test() {this. x=1;} var o=new test(); Alert (o.x); //The running result is 1. To indicate that this is not a global object at this point, I made some changes to the code: var x=2; Function test() {this. x=1;} var o=new test(); Alert (x); //The result of running 2 is 2, indicating that the value of the global variable x has not changed at all. Scenario 4: Using ‘apply()’ is a method of a function object that changes the calling object of the function. Its first parameter represents the changed calling object of the function. Therefore, this refers to the first parameter. Var x=0; Function test() {alert (this. x);} var o={}; o. X=1; o. M=test; o. M.application(); //When the parameter of 0 application() is empty, the global object is called by default. Therefore, the running result at this point is 0, which proves that this refers to the global object. If the last line of code is modified to o.m.apply (o); //The result of running 1 becomes 1, which proves that this represents the object o.