用var声明的变量的作用域是它当前的执行上下文,它可以是嵌套的函数,也可以是声明在任何函数外的变量。let和const是块级作用域,意味着它们只能在最近的一组花括号(function、if-else 代码块或 for 循环中)中访问。1
2
3
4
5
6
7
8
9
10
11
12
13
14function foo() {
// 所有变量在函数中都可访问
var bar = 'bar';
let baz = 'baz';
const qux = 'qux';
console.log(bar); // bar
console.log(baz); // baz
console.log(qux); // qux
}
console.log(bar); // ReferenceError: bar is not defined
console.log(baz); // ReferenceError: baz is not defined
console.log(qux); // ReferenceError: qux is not defined
1 | if (true) { |
var会使变量提升,这意味着变量可以在声明之前使用。let和const不会使变量提升,提前使用会报错。
1 | console.log(foo); // undefined |
用var重复声明不会报错,但let和const会。
1 | var foo = 'foo'; |
let和const的区别在于:let允许多次赋值,而const只允许一次。
1 | // 这样不会报错。 |