var foo = \'bar\';
console.log(window.foo); // bar
Seems like variables get assigned as properties to this
, but inside anonymous funct
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.
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.
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 aVariable object
. This is precisely why variables or functions declared globally become properties of aGlobal object
Yet, these Variable Object
s 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.
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).