Mailing List Archive
tlug.jp Mailing List tlug archive tlug Mailing List Archive
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]Re: [tlug] Variable scope in Javascript driving me nuts
- Date: Fri, 27 Aug 2010 02:28:50 +0900
- From: Romeo Theriault <romeo.theriault@example.com>
- Subject: Re: [tlug] Variable scope in Javascript driving me nuts
- References: <4C769657.5040705@example.com>
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.
- Follow-Ups:
- Re: [tlug] Variable scope in Javascript driving me nuts
- From: Darren Cook
- Re: [tlug] Variable scope in Javascript driving me nuts
- From: Josh Glover
- References:
- [tlug] Variable scope in Javascript driving me nuts
- From: Dave M G
Home | Main Index | Thread Index
- Prev by Date: Re: [tlug] Variable scope in Javascript driving me nuts
- Next by Date: Re: [tlug] Die, "Adobe Bridge Workspace File"! Die!
- Previous by thread: Re: [tlug] Variable scope in Javascript driving me nuts [SOLVED]
- Next by thread: Re: [tlug] Variable scope in Javascript driving me nuts
- Index(es):
Home Page Mailing List Linux and Japan TLUG Members Links