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 01:29, Dave M G <dave@example.com> wrote:
TLUG,

Arrgh! This just makes no sense to me. Here's my code:

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);
   }
   console.log ("valid OUTSIDE checkResult = " + valid);
   return valid;
}

When I run this, this is what I see in the console log:

valid OUTSIDE checkResult = false
jsonDataReceived.valid = true
valid inside checkResult = true

Shouldn't what happens inside the checkResult function set "valid" to
true before I get to the "return valid" part?


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. You could try making them both global or probably better yet, just pass the value back out of the function. 


Home | Main Index | Thread Index

Home Page Mailing List Linux and Japan TLUG Members Links