In non-strict mode, when a function is called without setting the this
value, it will become the global object:
10.4.3 Entering Function Code
- If the function code is strict code, set the ThisBinding to thisArg.
- Else if thisArg is null or undefined, set the ThisBinding to the
global object.
Therefore, the this
keyword may be way to obtain a reference to the global object:
this; // the global object
The first problem is that this
could have been customized (e.g. with apply
or call
):
(function() {
this; // `123`, not the global object!
}).call(123);
This can be easily fixed using a self-executing function:
// `this` may not be the global object here
(function() {
this; // the global object
})();
But there is a more serious problem: this
doesn't become the global object in strict mode:
'use strict';
(function() {
this; // `undefined`, not the global object!
})();
To fix that, you can use a Function Constructor. Even inside strict mode, the new function will be non-strict by default.
'use strict';
(function() {
new Function("return this")(); // the global object
})();