JavaScript has its own set of this mechanism, in different cases, this point is not the same.
Global scope
Console.log (this); Global variables
The global scope uses this to point to the global variable, which is window in the browser environment.
Note: The ECMAScript5 strict mode does not have global variables, here is undefined.
In a function call
function foo () {
console.log (this);
}
Foo (); Global variables
This in the function call also points to the global variable.
Note: The ECMAScript5 strict mode does not have global variables, here is undefined.
Object method call
var test = {
foo:function () {
console.log (this);
}
}
Test.foo (); Test object
Object method call, this points to the caller.
var test = {
foo:function () {
console.log (this);
}
}
var test2 = Test.foo;
Test2 (); Global variables
However, because of this late binding attribute, in the case of the example, this will point to the global variable, which is equivalent to calling the function directly.
This is very important, the same code snippet, only at run time can you determine this point
Constructors
function Foo () {
console.log (this);
}
New Foo (); The newly created object
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 Object
The call or Apply method using Function.prototype is that the inside of the function is set to the first argument passed in.