This is the keyword of JS, and the This value will change as the function is used in different situations. But the general principle is that this always points to the object that is calling this function .
1. Pure function call
function Test () {this. X=1; alert (x);} test ();
This is the global variable. The following example is a good way to understand that this is a global object.
var x=1; function Test () { alert (this. x);} Test (); // 1 var x=1; function Test () { this.x=0;} Test (); alert (x); // 0
In JavaScript's variable scope, "Global variables are all properties of a Window object." "So executing test () is equivalent to Window.test (), at which point the This keyword in the test function body becomes the window object. The X of the Window object will be changed to 0.
var x=1; var b={ x:2, GetX:function() { return this. x; }}; Alert (this. x); // 1 // 2
In the above code, alert (this.x) in the this point to the window, so in the global search for the value of x, is 1;
Alert (B.getx ()) is called with the function of X as Object B, this points to B, so the value of x is searched for in B, which is 2.
2, as a method invocation, then this refers to the object that invokes the method.
function Test () {alert (this. x);} var o={};o.x=1; o.m=test;o.m (); // 1
3. Called as a constructor function. This point points to the newly generated object.
function Test () { this. x=1;} var 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 0={};o.x=1; o.m=test (); o.m.apply (); // 0o.m.apply (o); // 1
When apply has no parameters, it is represented as a global object. So the value is 0.
The pointer to this in JavaScript