Let's see what happens if you specify this
in the function not bound to any element, like this:
function func() {
console.log(this);
}
func();
In this case, the result depends on whether we have a
strict
mode or not. If the mode is non-strict, then this
will store a reference to window
:
function func() {
console.log(this); // reference to the window
}
func();
And if the mode is strict, then undefined
will be stored in this
:
"use strict";
function func() {
console.log(this); // undefined
}
func();
From the above it would seem that in strict mode
this
will always be undefined
. It's
not the case! If you just output this
outside
the function, then it will have a reference to
window
regardless of the mode:
"use strict";
console.log(this); // there is reference to the window in this
Summary
You can write this
in any function without
causing any JavaScript errors. But what exactly will
lie in this
is not defined until the moment
the function is called. Moreover, with different
function calls, this
can be different values.
It all depends on the context in which the
function was called.