I'm trying to wrap my head around a scope issue. Take the two examples:
a)
var sels = ['.a', '.b', '.c'];
while ( (var sel = fieldsets.shift()) !== undefined ) {
(function(sel) {
$(sel).click(function() {
console.log(sel);
});
})(sel);
}
In this example, when one of the referenced elements is clicked, the output will be .a
, .b
, or .c
.
b)
var sels = ['.a', '.b', '.c'];
while ( (var sel = fieldsets.shift()) !== undefined ) {
$(sel).click(function() {
console.log(sel);
});
}
In this example, a click will result with undefined
.
I'm clearly misunderstanding how scope is applied in these two examples, because as I see it, when .click
is called in either case, sel
no longer exists at all.
What is the difference in the way scope is applied between these two cases?