Console.log (this); // window
function Xioahua () { Console.log (this);} Xiaohua (); // normal function call // window
' Use strict 'function Xiaohua () { Console.log (this);} Xiaohua (); // function calls in strict mode // undefined (function Xiaohua () { ' use strict ' console.log (this ); }) ()// let him call in strict mode immediately //undefind
var obj={ name:' Xiaohua ', foo:function() { Console.log ( This . Name) }} Obj.foo (); // method Invocation as an object // Xiaohua
function Test () { Console.log (this. name);} var obj={ name:' Xiaohua ', foo:test}obj.foo (); // method Invocation as an object // Xiaohua // explanation: Same as the same, because in JS everything is an object, the function is an object, for test, it is just a function name
, a reference to the function, which points to this function, when foo = Test,foo also points to the function. If you assign the object's method to
Value to a variable, and then call the variable directly:
var obj={ name:' Xiaohua ', foo:function() { Console.log ( This ); } } var xiaohuadawang=Obj.foo;xiaohuadawang (); // method Invocation as an object // Window // Explanation: You can see that this time this is performed globally, when we put test = Obj.foo, test directly points to a reference to a function
, this is not actually related to obj, so it is called directly as a normal function, so this is a pointer to the global object.
varobj={name:' Xiaohua ', foo:function() {Console.log ( This); }, Foo2:function() {Console.log ( This); SetTimeout ( This. foo,100); }}obj.foo2 ();//obj ...//window//Explanation: Executing this code we will find that two times the print out of this is not the same:
For the first time, this is printed directly in Foo2, which points to the Obj object, which we have no doubt;
But the this.foo that executes in setTimeout points to the global object, which is not
Use as a function method? This is often confusing to many beginners; in fact, SetTimeout is only
is a function, and the function is bound to require arguments, and we pass This.foo as a parameter to
SetTimeout This function, just as it needs a fun parameter, when passing in arguments, actually doing
A such operation fun = This.foo, see no, here we direct the fun point this
The. Foo reference; execution is actually a fun () so it has nothing to do with obj, it is
Called directly as a normal function, so this is a pointer to a global object. This problem is a lot of asynchronous callback letters
A common encounter in a number;
The This in JavaScript