An internal object that is automatically generated when the function is run, and can only be used inside the function
As the function is used differently, the value of this also changes, but there is a general principle:This refers to the object that called the function (CORE)
The This object points to
In general, we will analyze from the following four aspects
1. Pure function call
For example
1 function Test () {2 this. x = 1; 3 Alert (this. x); 4 this. x = 2; 5 }6 test (); // 17 alert (x); // 2
So here, this refers to the global object
There's another situation here, and a lot of people will be mistaken.
var x = 2; function Test () { var x = 1; function error () { alert (this. x); } return error;} Test (); // 2
In this case this is still the global object, because calling it is still a global object
2. Method invocation as an object
For example
1 var demo = {2 x:1,3 function () {4 var x = 2; 5 Alert (This. x)6 }7}; 8 demo.error (); // 1
This one here is pointing to the object demo.
And there's a confusing example.
1 varx = 3;2 varDemo = {3X:1,4Error:function () {5 varx = 2;6 functionSS () {7Alert This. x);8 }9 returnSS;Ten } One }; ADemo.error () ();//3
This here again points to the global object ..... A different way of looking may be clearer
1 (Demo.error ()) (); // think of () as a function, actually call this function or global object
Or another way of writing.
1 varx = 3; 2varDemo = { 3 x:1, 4 Error:function () { 5varx = 2; 6functionSS () {7 Alert ( This. x); 8 } 9 SS ();//3 No matter where the function is, as long as it is called a global object, this points to the global object10 }11 };Demo.error ();//3
3. Call as a constructor function
For example
1 function Test () {2 this. x = 1; 3 }4 varnew test (); 5 var x = 2; 6 alert (o.x); // 1
This side of this will point to the new object o
4. Call () and apply ()
For example
1 varx = 3;2 varo = {3X:14 };5 varv = {6X:2,7Testfunction () {8 return This. x;9 }Ten }; OneAlert (V.test ());//2 this point v AAlert (V.test.call ());//3 This points to the global -Alert (V.test.call (o));//1 this point o
When you use call and apply, what is the object in (), and this points to what object
JavaScript This object