ripper234
ripper234

Reputation: 230156

In strict mode, what is considered to be "gaining access to the global object"?

http://jsbin.com/ifabem/2/edit

"use strict";

window.x = "Hello World";
alert(x); // this does't throw an exception in strict mode

Why doesn't accessing x directly in the last statement violate strict mode and throw an exception?

Is it the case that a violating is only writing a new value into the global object, but reading and even modifying an existing object allowed?

Upvotes: 2

Views: 250

Answers (3)

kennebec
kennebec

Reputation: 104800

undeclared globals (variables instantiated without var in functions) are one instance,

another is that the methods call and apply no longer convert a primitive to a global object-(where a string becomes String, and null or undefined pass window) as the 'this' value.

Upvotes: 0

KooiInc
KooiInc

Reputation: 122936

I think by 'gaining access to the global object' is meant gaining access to it from within a non global object/scope. So this will throw a reference error:

function foo(){
 "use strict";
 bar = '3';
}
foo(); //=> ReferenceError: bar is not defined

In other words I would say, 'strict mode' enforces the assignment of variables within their own scope. That's why window.x is perfectly possible.

On the other hand, one can address window from within a function:

function foo(){
 "use strict";
 window.bar = '3';
}
foo();      //=> no error
alert(bar); //=> 3

So, in essence, use strict prevents declaring variables without the keyword var or without a reference to their own namespace within a non global scope.

Upvotes: 1

ruakh
ruakh

Reputation: 183446

The phrase "gaining access to the global object" does not occur in the spec, so doesn't have a clear definition; but looking through Appendix C of the spec (a non-normative listing of the effects of strict-mode), the only restriction that I think could be described that way is this one:

Assignment to an undeclared identifier or otherwise unresolvable reference does not create a property in the global object. When a simple assignment occurs within strict mode code, its LeftHandSide must not evaluate to an unresolvable Reference. If it does a ReferenceError exception is thrown (8.7.2).

So you're not allowed to add a property to the global object without using var or window. or whatnot, but there's nothing to stop you from getting a property of the global object — or even setting the value of an existing property.

(By the way, the relevant bit of §8.7.2 is not terribly meaningful out-of-context, but for completeness' sake, it's this:

3. If IsUnresolvableReference(V), then
    a. If IsStrictReference(V) is true, then
        i. Throw ReferenceError exception.
    b. Call the [[Put]] internal method of the global object, passing
        GetReferencedName(V) for the property name, W for the value,
        and false for the Throw flag.

)

Upvotes: 2

Related Questions