This is a keyword in the JavaScript language.
it represents an internal object that is automatically generated when the function is run, and can only be used inside the function. For example,
Copy CodeThe code is as follows:
function Test () {
this.x = 1;
}
The value of this will change as the function is used in different situations. But there is a general principle, that is, this refers to the object that called the function.
the use of this is discussed in detail in four scenarios.
case One: purely function calls
This is the most common use of a function, which is a global call, so this represents the Globals object.
take a look at the code below, which results in a 1 operation.
Copy CodeThe code is as follows:
function Test () {
this.x = 1;
alert (this.x);
}
Test (); 1
to prove that this is a global object, I make some changes to the code:
Copy CodeThe code is as follows:
var x = 1;
function Test () {
alert (this.x);
}
Test (); 1
The result of the operation is still 1. Change it a little bit again:
Copy CodeThe code is as follows:
var x = 1;
function Test () {
this.x = 0;
}
Test ();
alert (x); 0
Scenario Two: Invocation as an object method
a function can also act as a method call to an object, at which point this is the ancestor object.
Copy CodeThe code is as follows:
function Test () {
alert (this.x);
}
var o = {};
o.x = 1;
O.M = test;
O.M (); 1
scenario Three is called as a constructor function
The so-called constructor is to generate a new object by this function (object). At this point, this is the new object.
Copy CodeThe code is as follows:
function Test () {
this.x = 1;
}
var o = new Test ();
alert (o.x); 1
The run result is 1. To show that this is not a global object, I make some changes to the code:
Copy CodeThe code is as follows:
var x = 2;
function Test () {
this.x = 1;
}
var o = new Test ();
alert (x); 2
The run result is 2, indicating that the value of global variable x does not change at all.
scenario four apply call
apply () is a method of a function object that changes the calling object of a function, and its first parameter represents the changed object that called the function. Therefore, this is the first parameter.
Copy CodeThe code is as follows:
var x = 0;
function Test () {
alert (this.x);
}
var o={};
o.x = 1;
O.M = test;
O.m.apply (); 0
the global object is called by default when the argument to apply () is empty. Therefore, the result of this operation is 0, which proves that this refers to the global object.
if the last line of code is modified to
Copy CodeThe code is as follows:
O.m.apply (o); 1
The result of the operation becomes 1, which proves that this is the object o
The This keyword in JS is detailed