A function call, at which point this is the global window
1 var c=function () {2 alert (this = =window)3 } 4 C ()//true
Second, method invocation
var myobj={ value:2, inc:function (num) { alert (this. value+num); } } myobject.inc (1// result 3, because this points to myobj
Note: The internal anonymous function does not belong to the current object's function, so this refers to the Global object window
varmyobj={name:'MyObject', Value:0, increment:function (num) { This. Value + =typeof(num) = = =' Number'? Num:0; }, Tostring:function () {return '[object:'+ This. name+'{value:'+ This. value+'}]'; }, Getinfo:function () {return(function () {return This. toString ();//The internal anonymous function does not belong to the current object's function, so this is a pointer to the Global object window })(); }}alert (Myobj.getinfo ());//[Object window];
Workaround:
varmyobj={name:'MyObject', Value:0, increment:function (num) { This. Value + =typeof(num) = = =' Number'? Num:0; }, Tostring:function () {return '[object:'+ This. name+'{value:'+ This. value+'}]'; }, Getinfo:function () {varthis= This;//Save the current this point first . return(function () {returnthis.tostring (); })(); }}alert (Myobj.getinfo ());//[Object:myobject {value:0}]
Third, use the new keyword to create a new function object call, this point is bound to the instance of the constructor
var fn = function (status) { this. Status== function () { return thisvarnew fn ('my status' ); alert (test.get_status); // my status,this points to test
Four, Apply/call call
function MyObject (name) { This. name=name | |'MyObject'; This. value=0; This. increment=function (num) { This. Value + =typeof(num) = = =' Number'? Num:0; }; This. tostring=function () {return '[Object:'+ This. name+'{value:'+ This. value+'}]'; }; This. target= This; } function GetInfo () {return This. toString ();} varmyobj=NewMyObject (); Alert (getinfo.apply (MYOBJ));//[Object:myobject {value:0}],this points to myobjAlert (getinfo.apply (window));//[Object Window],this point to Window
Using call and apply, you can redefine the execution environment of the function, which is the point of this, which is very common for some applications.
The four ways to call the JS function and the corresponding this point