注:es6新增了块级作用域,其中if语句和for语句属于块级作用域。
举例子:
<script>
//块级作用域
{
var a = 1;
let b = 2;
const c = 3;
c = 4; //报错
var aa;
let bb;
//const cc;//报错
console.log(a);//1
console.log(b);//2
console.log(c);//3
console.log(aa);//undefined
console.log(bb);//undefined
}
console.log(a);//1
//console.log(b);//报错
//console.log(c);//报错
//函数作用域
(function A(){
var d = 5;
let e = 6;
const f = 7;
console.log(d);//5
console.log(e);//6 (在同一个{}中,也属于同一个块,可以正常访问)
console.log(f);//7(在同一个{}中,也属于同一个块,可以正常访问)
})();
//console.log(d);//报错
//console.log(e);//报错
//console.log(f);//报错
</script>