I have seen anonymous functions inside for loops to induce new scope on the web in one or two places and would like to know if it makes sense.
for example:
var attr, colors = ['green','blue','red'];
for ( attr = 0; attr < colors.length; attr++) {
(function() {
var colorAttr = colors[attr];
// do something with colorAttr
})();
}
I understand it has something to do with keeping the scope inside the for loop clean, but in what situations would this be necessary? Would it be good practice to do this everywhere you need to declare a new var inside the for loop?
attr
changes as the loop progresses, so if you usecolors[attr]
in a callback function, it won't refer to thecolors[attr]
that you actually want. – Blender Dec 20 '12 at 17:05colors[]
changes. – mkey Dec 20 '12 at 17:07colorAttr
is scoped to that immediately executing function, but it can walk up to the parent scope and happily accessattr
. – Steve Fenton Dec 20 '12 at 17:09