Cameron Martin
Cameron Martin

Reputation: 6012

Why do variables in the global scope get assigned to the window object?

var foo = 'bar';
console.log(window.foo); // bar

Seems like variables get assigned as properties to this, but inside anonymous functions, this refers to the parent scope, but doesn't assign variables to the parent scope.

function() {
    var foo = 'bar';
}();

window.foo; // undefined

What object do variables get assigned to in non-global scopes?

Upvotes: 3

Views: 544

Answers (4)

Bergi
Bergi

Reputation: 664548

To cite http://perfectionkills.com/understanding-delete/#execution_context:

Every execution context has a so-called Variable Object associated with it. Similarly to execution context, Variable object is an abstract entity, a mechanism to describe variable instantiation. Now, the interesing part is that variables and functions declared in a source text are actually added as properties of this Variable object.

When control enters execution context for Global code, a Global object is used as a Variable object. This is precisely why variables or functions declared globally become properties of a Global object

Yet, these Variable Objects are not accessible. The only non-internal one is the global object, window or this (in global context).

The relevant section in the specification is #10: Executable Code and Execution Contexts.

Upvotes: 5

Mattias Buelens
Mattias Buelens

Reputation: 20159

In JavaScript, all variables are assigned to some scope object. However, only the scope object of global variables is accessible in JavaScript in the browser through the window object. Variables in a function scope are assigned to some scope object used internally by the JavaScript runtime, but this cannot be accessed by the user.

In another environment, global variables may be accessible as properties of another object (such as GLOBAL in node.js) or may be inaccessible (such as application scripts running inside the Windows Script Host).

Upvotes: 2

Sarfraz
Sarfraz

Reputation: 382726

Inside self-invoking anonymous function eg:

function() {
    ....
}()

All variables remain inside it and do not attach themselves to global object or window. Using that technique, there are patterns created such as module/singleton pattern.

Notice that in JS, variables have function-level scope.

Upvotes: 0

Dave Newton
Dave Newton

Reputation: 160191

They're available only in the function they're declared in.

Function scope is the only other scope in JavaScript, btw, unlike block-scoping in other {} languages.)

Re: your edit Don't be fooled--JS's this semantics are a bit irksome IMO--this may not be what you expect under a variety of circumstances.

Upvotes: 0

Related Questions