Javascript中只有两种作用域,函数作用域和全局作用域。没错,块(如while,if,for语句)则没有自己的作用域。以下为代码验证:
<script>
//JavaScript中只有两种作用域:函数作用域和全局作用域。函数拥有自己的作用域,而块(如while, if, for语句)则没有。
var foo = 'test';
if (true){
//注意:此处都属于全局变量
var foo2 = 'new test';
var foo = 'old test';
}
console.log(foo2); //从这里可以看出在if中定义的变量是全局变量
console.log(foo); //old test
function test(){
var foo = 'testing';
}
test(); //调用函数,但函数中定义的foo只是局部变量,不能影响外面的foo
console.log(foo);
</script>