JavaScript has its own set of this mechanism. In different situations, the pointing of this is also different.
Global scope
console.log(this); //全局变量
The global scope uses this to point to global variables, which is window in the browser environment.
Note: ECMAScript5’s strict mode does not have global variables, and this here is undefined.
Function calling
function foo() { console.log(this); } foo(); //全局变量
This in function calls also points to global variables.
Note: ECMAScript5’s strict mode does not have global variables, and this here is undefined.
Object method call
var test = { foo: function () { console.log(this); } } test.foo(); //test对象
In object method calls, this points to the caller.
var test = { foo: function () { console.log(this); } } var test2 = test.foo; test2(); //全局变量
However, due to the late binding feature of this, in the above example, this will point to the global variable, which is equivalent to calling the function directly.
This is very important. The same code segment can only be determined when running
Constructor
function Foo() { console.log(this); } new Foo(); //新创建的对象 console.log(foo);
Inside the constructor, this points to the newly created object.
Explicitly set this
function foo(a, b) { console.log(this); } var bar = {}; foo.apply(bar, [1, 2]); //bar foo.call(1, 2); //Number对象
When using the call or apply method of Function.prototype, this inside the function will be set as the first parameter passed in.