Skip to content Skip to sidebar Skip to footer

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 does

Solution 1:

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.


Solution 2:

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).


Solution 3:

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.


Solution 4:

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.


Post a Comment for "Why Do Variables In The Global Scope Get Assigned To The Window Object?"