In the browser, it is expected that this
, inside an IIFE, points to the window object. However, it is undefined in this case.
(function () {
"use strict";
console.log(this) // undefined
// more stuff
}());
In the browser, it is expected that this
, inside an IIFE, points to the window object. However, it is undefined in this case.
(function () {
"use strict";
console.log(this) // undefined
// more stuff
}());
In ECMAScript 5's strict mode only, when the value of this
is undefined or null (i.e. when not in an object's scope or this
is explicitly set), this
will not return the global object from the function scope.
What actually happens when a function is called is the following - the ThisBinding
is jargon for the value of this
when called (ECMA-262).
10.4.3 Entering Function Code
The following steps are performed when control enters the execution context for function code contained in function object F, a caller provided thisArg, and a caller provided argumentsList:
1. If the function code is strict code, set the ThisBinding to thisArg.
2. Else if thisArg is null or undefined, set the ThisBinding to the global object.
If you want the global object, you can use a global variable that is defined in the global scope or use some hacks around this, such as using an immediately invoked new Function()
1.
1: Using new Function()
works as it does not go into strict mode unless the function has the pragma 'use strict';
within the body of the new Function()
itself (reference).
One way to pass the global object in explicitly in strict mode is to use call(this)
(function(){
"use strict";
console.log(this) // this points to window
// more stuff
}).call(this);
From MDN, under "Securing" JavaScript
First, the value passed as this to a function in strict mode isn't boxed into an object. For a normal function, this is always an object: the provided object if called with an object-valued this; the value, boxed, if called with a Boolean, string, or number this; or the global object if called with an undefined or null this. (Use call, apply, or bind to specify a particular this.) Automatic boxing is a performance cost, but exposing the global object in browsers is a security hazard, because the global object provides access to functionality "secure" JavaScript environments must restrict. Thus for a strict mode function, the specified this is used unchanged:
Example:
"use strict";
function fun() { return this; }
assert(fun() === undefined);
assert(fun.call(2) === 2);
assert(fun.apply(null) === null);
assert(fun.call(undefined) === undefined);
assert(fun.bind(true)() === true);