由于涉及两个单独的函数,即即使变量都使用它,变量也不应该在不同的范围内_GetFoo
吗_CountBar
?bar
如果您复制粘贴它然后运行它,它将显示两个警报的问题。
<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>
为什么要共享范围_GetFoo
?_CountBar