在javascript的ES6版本之前,只使用关键字var来声明变量。
在ES6版本中,引入了关键字let和const来声明变量。
| 关键字 | var | let | const |
|---|---|---|---|
| 全局作用域 | 是 | 否 | 否 |
| 函数作用域 | 是 | 是 | 是 |
| 块作用域 | 否 | 是 | 是 |
| 重复声明 | 是 | 是 | 否 |
全局作用域
let不是全局作用域,不会挂载到window对象。
var a1 = 123;
let a2 = 999;
function show(){
console.log(a1); // 123
console.log(a2); // 999
}
show();
// window 是系统全局变量
window.a1; // 123
window.a2; // undefined 函数作用域
var和let函数作用域相同,外部不能调用内部变量。
function temp(){
let a1 = "hello";
var a2 = "world";
}
console.log(a1); // Uncaught ReferenceError: a1 is not defined
console.log(a2); // Uncaught ReferenceError: a2 is not defined块作用域
在javascript中,代码块指的是写在花括号{}中的代码。
var比let高级,在块范围内用let关键字声明的变量不能从块外部访问。
{
var a1 = [1, 2, 3];
}
console.log(a1); // [1,2,3]
{
let a2 = [11, 22, 33];
}
console.log(a2); // Uncaught ReferenceError: a2 is not defined重复声明
使用const关键字的变量的行为与使用let关键字声明的变量完全相同,只是有一点不同,任何使用const关键字声明的变量都不能被重新赋值。
const x = { name: "tom" };
x = { address: "seo" }; // error: Assignment to constant variable.
x.name = "lucy"; // No error