let和const

173 阅读2分钟

let和const命令

let

{
let b = 1
var c = 2
}
b // ReferenceError: b is not defined
//let声明变量只在它所在的代码块有效
c // 2

之前遇到的for循坏问题,let就能解决

for(var i = 0 ; i < 5; i++){
setTimeout(()=>{
console.log(i)
})
}
// 5 5 5 5 5
for(let i = 0 ; i < 5; i++){
setTimeout(()=>{
console.log(i)
})
}
// 0 1 2 3 4

不存在变量提升

console.log(d)
let d = 3
//ReferenceError: d is not defined
--------------------------
console.log(d)
var d = 3
//undefined

暂时性死区

在使用let声明变量之前,该变量都是不可用的

if(true){
tmp = 'abc' //ReferenceError
console.log(tmp) //ReferenceError

let tmp
console.log(tmp)//undefined

tmp = '123'
console.log(tmp) //123
}
function bar(x=y,y=2){
return [x,y]
}
bar()
//ReferenceError: Cannot access 'y' before initialization
//y在未声明前赋值给x,属于死区
function bar(x=2,y=x){
return [x,y]
}
bar()
// [2,2]

总结:暂时性死区的本质——只要一进入当前作用域,所要使用的变量就已经存在了,只是不可获取,声明变量的代码出现后,才可以获取和使用该变量。

不允许重复声明

不允许在相同作用域内重复声明同一个变量

{
let a = 1
let a = 2
}
//Uncaught SyntaxError: Identifier 'a' has already been declared
-----------------------------------
{
var a = 1
var a = 2
}
a//2

可以

{
let a = 1
{
let a = 2
}
}
//在不同作用域内

块级作用域

  • ES5只有全局作用域和函数作用域,没有块级作用域
  • ES6 let为JavaScript新增了块级作用域

避免在块级作用域内声明函数,如果确实需要,应写成函数表达式而不是函数声明语句

const命令

声明一个只读的常量。

一旦声明,常量的值就不能改变。

const a = 1
a = 2
//TypeError: Assignment to constant variable.
a // 1

const不能只声明不赋值

const b
//SyntaxError: Missing initializer in const declaration

与let一样,只在声明所在块级作用域内有效

{
const a = 1
}
a//ReferenceError: a is not defined

暂存性死区

{
console.log(a)
const a = 1
}
//ReferenceError: Cannot access 'a' before initialization

不允许重复声明

const a = 1
const a = 2
//Uncaught SyntaxError: Identifier 'a' has already been declared

ES6 声明变量的六种方法

  • var
  • function
  • let
  • const
  • import
  • class