Consider the following code snippet:
var global = (function(){
return this;
}());
When this executes global will point to window object in browser.
But this doesn't work in strict mode. Why?
Consider the following code snippet:
var global = (function(){
return this;
}());
When this executes global will point to window object in browser.
But this doesn't work in strict mode. Why?
The ES5 specification allows you to retrieve the global object through an indirect eval.
var global = (0, eval)('this');
This works in both strict and non-strict mode.
An indirect eval is basically a call to eval made by value rather than reference (or without the name of the value binding being "eval"). Indirect eval is executed in global scope, and this in global scope refers to the global object.
There is a detailed article covering this at: http://perfectionkills.com/global-eval-what-are-the-options/
The reason was already explained by dystroy: this will not be the global object in strict mode. Here is the workaround (assuming that's running on the global scope):
var global = (function(g){
return g;
}(this));
The reason, according to the ES5 specification, is:
If
thisis evaluated within strict mode code, then thethisvalue is not coerced to an object. Athisvalue ofnullorundefinedis not converted to the global object
From the MDN :
for a strict mode function, the specified this is used unchanged:
...
"use strict";
function fun() { return this; }
assert(fun() === undefined);
So this is exactly as specified.