This Keyword
In most cases, the value ofthis
is determined by how a function is called. It can't be set by assignment during execution, and it may be different each time the function is called.
Function Context
Inside a function, the value ofthis
depends on how the function is called.
Simple Call
Since the following code is not in strict mode, and because the value ofthis
is not set by the call, this
will default to the global object.
function f1(){
return this;
}
// In a browser:
f1() === window; // the window is the global object in browsers
// In Node:
f1() === global
In strict mode, however, the value ofthis
remains at whatever it was set to when entering the execution context, so, in the following case,this
will default toundefined
function f2(){
"use strict"; // see strict mode
return this;
}
f2() === undefined;
As an object method
When a function is called as a method of an object, itsthis
is set to the object the method is called on.
var o = {
prop: 37,
f: function() {
return this.prop;
}
};
console.log(o.f()); // logs 37
So we use the “this” keyword not only for aesthetics (i.e., as a referent), but also for precision; its use actually makes our code more unambiguous, just as the pronoun “he” made our sentence more clear. The this keyword not only refers to the object but it also contains the value of the object.
Note that when we use strict mode, this holds the value of undefined in global functions and in anonymous functions that are not bound to any object.