let
let 允许把变量的作用域限制在块级域中。与 var 不同处是:var 申明变量要么是全局的,要么是函数级的,而无法是块级的。
let vs var
let的作用域是块,而var的作用域是函数
'use strict';
var a = 5;
var b = 10;
if (a === 5) {
let a = 4; // The scope is inside the if-block
var b = 1; // The scope is inside the function
console.log(a); // 4
console.log(b); // 1
}
console.log(a); // 5
console.log(b); // 1
let在循环中
可以使用let关键字绑定变量在循环的范围而不是使用一个全局变量(使用var)定义。
'use strict';
for (let i = 0; i < 10; i++) {
console.log(i); // 0, 1, 2, 3, 4 ... 9
}
console.log(i); // i is not defined
上面报错,因为变量i不存在于for语句外的作用域中。let创建块级作用域变量的,使用var创建一个全局变量。
请按照上面的例子在for循环中分别用let与var定义i变量,并在循环外打印出结果,体会let与var作用域。