javascript:closures pitfall

by Mohan 2012-09-20 23:52:18


closures pitfall
var a = [];

for ( var i=0; i<10; i++ ) {

a[i] = function() { Print(i); }
}

a[0](); // is: 10
a[1](); // is: 10
a[2](); // is: 10
a[3](); // is: 10
simpler case:
var i = 5;
function foo() { Print(i) }
foo(); // prints 5
i = 6;
foo(); // prints 6


569
like
0
dislike
0
mail
flag

You must LOGIN to add comments