global object in strict mode

Brendan Eich brendan at
Fri Aug 24 11:30:04 PDT 2012

John J Barton wrote:
> On Fri, Aug 24, 2012 at 10:51 AM, Brendan Eich<brendan at>  wrote:
>> Kris Kowal wrote:
>>> On Fri, Aug 24, 2012 at 10:41 AM, Brendan Eich<brendan at>
>>> wrote:
>>>> I'm not sure what the problem is -- I read the old thread, and noticed
>>>> the
>>>> solution:
>>>> var global = Function("return this")();
>>>> This is good for any code mode, strict or non-strict. Does CSP ban
>>>> Function
>>>> as well as eval?
>>> CSP does forbid the Function constructor, by the edict “Code will not
>>> be created from strings”.
>>> Section 4.2 “If unsafe-eval is not allowed…”
>> Sure, makes sense (I think I even knew that once -- have to catch up on CSP
>> when I have some time, next millennium :-P).
> CSP creates another JS environment by banning certain JS features.

Ya I know (Mozilla started CSP), I was just being slow there ;-).

>> Is it common to want an expression, usable in any context (non-strict,
>> strict, CSP, deep in a function nest with potentially many names in scope,
>> some of which might shadow globals), that evaluates to "the current global
>> object"?
> I guess the purpose of "global" is to document dependency on the JS
> global objects but not on the rest of the global objects attached to
> |window|.

Mark's point overrides. If someone needs the global, there's a 
capability in non-SES JS: it must be handled carefully, though. That's 
the non-silly part of the non-problem I was describing :-|.

> (To your earlier question about the 'problem', my problem is simply to
> use some else's JS code in a CSP environment. It uses the eval form. I
> need to convince them of an alternative. But it seems like this will
> be a common problem, hence my post).

I'm not sure how common. Globals are considered harmful for good reason.

>> JS libraries do things like
>> (funciton (global) {
>>    // all the code here
>> })(this);
>> and that works, as well as the brute force
>> var global = this;
>> approach. But one must take care not to shadow the name.
> Perhaps that is the reason for the funky construct,
>   var global = ("global", eval)("this");

That's for inside a function. The comma-expression eval callee is to 
force indirect eval, which evaluates global code.

That pattern does not help avoid shadowing of names, of course. Non-strict outer code could even shadow 'eval' and make that code do other than what's expected. My point about shadowing was not meant to encourage a shadow-proof name for the global object, though.

Really, if you need the global, you can save 'this' at top level in a var you create, or pass it down to a function call. I know this does not help local needs for "the global object", but I suspect those are rare and should be recast anyway (Mark's point).


More information about the es-discuss mailing list