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 26 August 2010 18:28, Romeo Theriault <romeo.theriault@example.com> wrote:

> On Fri, Aug 27, 2010 at 01:29, Dave M G <dave@example.com> wrote:
>>
>> my function()
>> {
>>    var valid = false;
>>    string = JSON.stringify(data);
>>    $.post('jsonhandler.php', {JSON: string}, checkResult, "json");
>>    function checkResult(jsonDataReceived)
>>    {
>>       valid = jsonDataReceived.valid;
>>       console.log ("jsonDataReceived.valid = " + jsonDataReceived.valid);
>>       console.log ("valid inside checkResult = " + valid);
>>    }
>
> Just a guess but it looks like you're setting 'var valid = false;' inside a
> function as a local variable. That's what 'var' does in javascript I think.
> 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.

This is a related question for a language nerd: does Javascript have
closures at all? If anonymous functions are not the way to create a
closure, what is?

-- 
Cheers,
Josh


Home | Main Index | Thread Index

Home Page Mailing List Linux and Japan TLUG Members Links