Since there are two separate functions involved, namely _GetFoo and _CountBar shouldn't the variable bar be in a different scope even though they both use it? If you copy paste this and then run it, it will display the problem with two alerts.
<script type="text/javascript">
var example = function () {
var Foo = [];
function _BuildFoo(size) {
for (var buildSize = 0; buildSize < size; buildSize++) {
Foo.push(buildSize);
}
}
function _GetFoo(index) {
for (bar in Foo) {
//do Foo bar
}
}
function _CountBar() {
for (bar in Foo) {
alert(bar); //bar = 0
_GetFoo(1);
alert(bar); //bar is incremented from _GetFoo function and is now 19
break;
}
}
return {
_CountBar: _CountBar,
_BuildFoo: _BuildFoo
}
}
var foobar = new example();
foobar._BuildFoo(20);
foobar._CountBar();
</script>
Why do _GetFoo and _CountBar share scope?
baris attached to the global scope. Tryvar bar; for (bar in Foo) /* ... */instead :^)