This is a keyword in Javascript. It indicates an internal object automatically generated during function running and can only be used within the function. For example,
Function test (){
This. x = 1;
}
The value of this varies with the function usage. But there is a general principle, that is, this refers to the object that calls the function.
The following describes the usage of this in four cases.
Case 1: Pure function call
This is the most common function usage and is a Global call. Therefore, this indicates the Global object.
See the following code. The running result is 1.
Function test (){
This. x = 1;
Alert (this. x );
}
Test (); // 1
To prove that this is a global object, I made some changes to the Code:
Var x = 1;
Function test (){
Alert (this. x );
}
Test (); // 1
The running result is still 1. Change the following:
Var x = 1;
Function test (){
This. x = 0;
}
Test ();
Alert (x); // 0
Scenario 2: Call an object Method
A function can also be called as a method of an object. In this case, this refers to the parent object.
Function test (){
Alert (this. x );
}
Var o = {};
O. x = 1;
O. m = test;
O. m (); // 1
Case 3 as a constructor call
The so-called constructor generates a new object through this function ). This indicates the new object.
Function test (){
This. x = 1;
}
Var o = new test ();
Alert (o. x); // 1
The running result is 1. To show that this is not a global object, I made some changes to the Code:
Var x = 2;
Function test (){
This. x = 1;
}
Var o = new test ();
Alert (x); // 2
The running result is 2, indicating that the value of global variable x has not changed.
Case 4 apply call
Apply () is a method of a function object. Its function is to change the object called by the function. Its first parameter indicates the object called by the function after the change. Therefore, this is the first parameter.
Var x = 0;
Function test (){
Alert (this. x );
}
Var o = {};
O. x = 1;
O. m = test;
O. m. apply (); // 0
When the apply () parameter is null, The Global object is called by default. Therefore, the running result is 0, proving that this is a global object.
If you change the last line of code
O. m. apply (o); // 1
The running result is changed to 1, which proves that this represents the object o.
From Xu Yue's column