3

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?

bfavaretto
  • 71,580
  • 16
  • 111
  • 150
Abhijeet Pawar
  • 690
  • 6
  • 19

3 Answers3

10

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/

Nathan Wall
  • 10,530
  • 4
  • 24
  • 47
4

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 this is evaluated within strict mode code, then the this value is not coerced to an object. A this value of null or undefined is not converted to the global object

bfavaretto
  • 71,580
  • 16
  • 111
  • 150
1

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.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758