I've a variable scope problem and I don't understand why this occurs and how to get rid of it :
var items = ['foo', 'bar'];
for (var index in items) {
var item = items[index];
var selector = '.'+item+'-class';
$(selector).bind('click', function() {
console.log("class: "+$(this).attr('class'));
console.log("selector: "+selector);
console.log("item: "+item);
});
}
Considers that this code execute itself over the following HTML :
<div class="foo-class">Foo</div>
<div class="bar-class">Bar</div>
Clicking on "Foo" echoes the right class (i.e. "foo-class") in the first line but the selector and the item name following are related to bar. I think that the problem is that the second iteration of the loop reset the variables used in the first one.
I thought that the declaration inside of the loop should clearly declare their scope at this level. Am I wrong ? Why ? How can I fix it ?
I'm not seeking a workaround, I want something clean and a better comprehension of javascript variable scope mecanism.
Here the jsfiddle.
Thanks !