[Javascript] Help with closures

Nick Fitzsimons nick at nickfitz.co.uk
Fri Jan 12 14:00:15 CST 2007


On 12 Jan 2007, at 19:42:18, Bill Moseley wrote:

> I expected "item" to be a new variable every time through the loop.
> Isn't that what "var" means?
>
>         var item = 'item' + list[i];
>
> Yet, running the code "item" refers always to the last value, as shown
> in "Example 5".  It returns "item3" three times.

Variables in JavaScript are define as having function scope, not  
block scope. If defined outside a function definition, or defined  
within a function without the use of the "var" keyword, the have  
global scope. Thus:

var foo = 1;

alert(foo); // shows "1"

function testWithoutVar() {
    foo = 2; // no "var", so foo is the global foo
}

testWithoutVar();
alert(foo); // shows "2"

function testWithVar() {
    var foo = 3; // foo is local to the function
}

testWithoutVar();
alert(foo); // shows "2" as global foo is left unchanged by the function

function testWithBlock() {
    var bar = 1;
    for (var i = 0; i < 10; i++) {
       var bar = i; // this is just redefining the outer bar, not a  
new bar with block scope
    }
    alert(bar); // shows "9"
}

testWithBlock();
alert(bar); // shows "undefined", as bar only had function scope

Moral: just because the syntactic sugar in JavaScript is similar to C- 
style languages such as Java, doesn't mean it follows the same  
scoping rules. I would suggest having a look at ECMA 262, which  
defines the ECMAScript language of which JavaScript is an  
implementation, but nobody who's read it all the way through (several  
times) would willingly inflict it on another human being :-)

HTH,

Nick.
-- 
Nick Fitzsimons
http://www.nickfitz.co.uk/






More information about the Javascript mailing list