变量提升是什么?暂时性死区是什么?var、let、const的区别
变量提升
js
console.log(a) // undefined
var a = 1
👇 等价于
js
var a
console.log(a) // undefined
a = 1
声明的变量会被提升到作用域的顶部
🤔: 👇 重复声明会导致 a 输出什么
js
var a = 10
var a
console.log(a)
这里第二次声明并不会覆盖赋值为 undefined
因为等价于
js
var a
var a
a = 10
console.log(a)
函数提升
js
console.log(a) // ƒ a() {}
function a() {}
var a = 1
TODO: 待确认 等价于
js
var a
function a(){}
console.log(a)
a = 1
- 函数提升优先于变量提升
- 函数提升会把整个函数挪到作用域顶部(有值)
- 变量提升只会把声明挪到作用域顶部(无值)
let、const
👇 var
和 let
const
的区别
js
var a = 1
let b = 1
const c = 1
console.log(window.a) // 1
console.log(window.b) // undefined
console.log(window. c) // undefined
暂时性死区
js
var a = 1
function test(){
console.log(a)
let a
}
test()
👆 函数内的 a
,取不到函数外 var
声明的a 这就是暂时性死区,不能在声明前使用变量
在函数的作用域中,let
声明的变量是有提升的,但是 let
声明的变量访问是受限制的(不能在声明前使用变量)
在window
作用域下同理
let
、const
因为暂时性死区的原因,不能在声明前使用
变量提升的意义
把声明提升到作用域顶端, 才能让下面的声明前调用的代码生效
js
function test1() {
test2()
}
function test2() {
test1()
}
test1()