Ray wrote:
I think I've had JavaScript variable scope figured out, can you
please see if I've got it correctly?
* Variables can be local or global
Where 'local' means local to a function, but functions may be nested
and a variable local to a function that contains another may be visible
inside the contained function if not 'masked' by an identically named
local variable, formal parameter or inner function declaration within
the contained function.
* When a variable is declared outside any function, it is global
regardless of whether it's declared with or without "var"
If - var - is not used then a variable is not declared at all. You are
describing an assignment to an (undeclared) Identifier. The effect of
an assignment to an undeclared Identifier is the creation of a property
of the global object with a name corresponding with the Identifier, and
declaring a global variable also results in the creation of a property
of the global object, so the two seem similar. However, a variable
declaration results in the creation of a property on the pertinent
object (the global object in the case of a global variable) as code
enters the relevant execution context, while assigning to an undeclared
Identifier does not create a property of the global object until the
assignment. Also, the property resulting from a variable declaration
cannot be deleted, while a property resulting form assignment can be.
* When it is declared inside a function, if declared with "var", it's
local, if not, it's global
Without -var - the assignment to an undeclared Identifier results in
the creation of a property of the global object wherever it occurs (at
least without objects with property names corresponding with the
Identifier having been explicitly added to the scope chain with the -
with - statement).
* A local variable that is declared inside a function is local to the
whole function, regardless of where it is declared, e.g.:
Yes.
function blah() {
for(var i ... ) {
var j ...
}
}
i and j will both be visible within blah()
Yes.
after their declaration.
They are also visible before their declaration. All the declarations
for a function are processed prior to the execution of any function
body code.
* the notion of "function" in this context also applies for this kind
of construct:
var myHandler =
{
onClickDo: function()
{
in the sense that whatever one declares inside onClickDo with "var"
will only be visible inside onClickDo.
What else, am I missing anything?
Nested functions.
<URL:
http://www.jibbering.com/faq/faq_not...es.html#clScCh >
Richard.