This is a keyword of JS, and the value of this will change as the function is used in different situations. But there is always a principle that this refers to the object that invokes the function.
1, pure function call.
function Test () {
this.x = 1;
alert (x);
}
Test ();
Actually this is the global variable. Look at the following example to understand the fact that this is the global object.
var x = 1;
function Test () {
Alert (this.x);
}
Test (); //1
var x = 1;
function Test () {
this.x = 0;
}
Test ();
alert (x); //0
2, as a method call, then this refers to this ancestor object.
function Test () {
Alert (this.x);
}
var o = {};
o.x = 1;
O.M = test;
1
3. Called as a constructor function. The so-called constructor is the creation of a new object. At this point, this refers to this object.
function Test () {
this.x = 1;
}
New test ();
alert (o.x); //1
4. Apply Call
This points to the first parameter in apply.
var x = 0;
function Test () {
Alert (this.x);
}
var o = {};
o.x = 1;
O.M = test;
0
O.m.apply (o); //1
When apply has no parameters, it is represented as a global object. So the value is 0.
JS in this application