Mailing List Archive


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [tlug] Variable scope in Javascript driving me nuts



On Fri, Aug 27, 2010 at 08:33, Darren Cook <darren@example.com> wrote:
> Then inside your inner checkResult function it looks like you're setting
> 'valid' as a global function by not having any 'var' in front of it. So the
> checkResult's 'valid' variable is a global var and the 'my function()',
> 'valid' var is a local variable. You could try making them both global or
> probably better yet, just pass the value back out of the function.

No. This is the traditional programming language way of thinking.
_javascript_ uses what they call "closures", which means a function has
the ability to reference all variables in its scope at the point of
declaration.

When you reference a variable called "valid" in checkResult it first
checks the functions local variables it finds none. So it goes up to the
closure scope and finds "valid" there. If it didn't find it there it
would look in the global scope. And if it didn't find it there it would
create a new local (though you might get a warning about not using the
"var" keyword).

Ahh, good to know. Thanks for taking the time to point that out. 

Home | Main Index | Thread Index

Home Page Mailing List Linux and Japan TLUG Members Links