Wednesday 11 January 2012

Nested function variable scope in Javascript

The way scope works for nested functions in Javascript can trip you up:
#target photoshop
function test()
{
this.a10 = function()
{
a = 10;
this.a20();
return a;
}
this.a20 = function()
{
a = 20;
}
}
t = new test();
alert( t.a10() ); // Returns 20!
And now with the added "var" keyword:
#target photoshop
function test()
{
this.a10 = function()
{
var a = 10;
this.a20();
return a;
}
this.a20 = function()
{
var a = 20;
}
}
t = new test();
alert( t.a10() ); // Returns 10