The value of this is determined based upon where the function was called. Here is an example:
let foo = {
bar: this,
baz: function() {
console.log(this)
}
}
console.log(foo.bar); // logs window
foo.baz(); // logs foo
let hey = foo.baz;
hey(); // logs window
A new value of this
is created when a method is invoked on a object. Therefore, our first log logs window because we haven't invoked any method. However, our second example logs foo because now a method on foo is called and therefore the value of this
inside the baz function is foo. You can usually derive the value of this taking the object left of the dot of the function which is called.
For example foo.baz()
, foo is left of the dot of baz()
so foo is the value of this
.
The last example is a bit tricky. The function object gets stored inside the variable hey. Now when hey gets executed it will log window
. This is because the value of this is determined when hey()
gets executed. Because hey is a global variable it sits on the window object. Using the rule we just learned we can take the object left of the dot of hey()
. This is window, because all variables on the global scope are window.variable
.
If you fully want to understand the value of this you should also know how the execution context works in JS. Here is some information about that.