一、var " r1 O0 i/ ?* a) p 在ES5中,顶层对象的属性和全局变量是等价的,用var声明的变量既是全局变量,也是顶层变量。$ D! j% I. R, H7 X H; W
注意:顶层对象,在浏览器环境指的是window对象,在 Node 指的是global对象。: h8 ?/ p O4 {, F. ?
// var
console.log(a) // undefined
var a = 10
// let
console.log(b) // Cannot access 'b' before initialization
let b = 10
// const
console.log(c) // Cannot access 'c' before initialization
const c = 10
暂时性死区 A# c7 s' w y$ j' S$ a4 ]) E
var不存在暂时性死区,let和const存在暂时性死区,只有等到声明变量的那一行代码出现,才可以获取和使用该变量。 , E( c9 m9 l. W1 M
// var
console.log(a) // undefined
var a = 10
// let
console.log(b) // Cannot access 'b' before initialization
let b = 10
// const
console.log(c) // Cannot access 'c' before initialization
const c = 10
块级作用域 ( k( `% Q2 A3 N& {+ C var不存在块级作用域,let和const存在块级作用域。 " k5 _; s. l4 E; U$ V
// var
{
var a = 20
}
console.log(a) // 20
// let
{
let b = 20
}
console.log(b) // Uncaught ReferenceError: b is not defined
// const
{
const c = 20
}
console.log(c) // Uncaught ReferenceError: c is not defined
重复声明 * M+ _+ P% Q; c, t* F& ~/ n# z var允许重复声明变量,let和const在同一作用域不允许重复声明变量。 " M- O: _) l6 g/ F
// var
var a = 10
var a = 20 // 20
// let
let b = 10
let b = 20 // Identifier 'b' has already been declared
// const
const c = 10
const c = 20 // Identifier 'c' has already been declared
// var
var a = 10
a = 20
console.log(a) // 20
//let
let b = 10
b = 20
console.log(b) // 20
// const
const c = 10
c = 20
console.log(c) // Uncaught TypeError: Assignment to constant variable
使用 2 C# J$ x' \) r 能用const的情况尽量使用const,其他情况下大多数使用let,避免使用var。