b.splendous.net

scope in js

January 2011 / tech

This is a fun closures in JavaScript thing.

This doesn't do what you'd like (or at least it didn't do what I'd have liked):

var entries = ['a', 'b', 'c'];
for (i in entries) {
var entry = entries[i];
$('#a'+entry).click(function() {
alert('entry: '+entry);
});
}

No matter what you click on, it'll display 'c' - that was the last entry in the function scope, so that's what has been stored as the scope.

You can get around this by adding another function, and calling it immediately. This way, your scope is preserved:

var entries = ['a', 'b', 'c'];
for (i in entries) {
var entry = entries[i];
$('#a'+entry).click(function() {
return function(entry) {
alert('entry: '+entry);
}(entry);
});
}

Fun!