JS变量提升

134 阅读1分钟

来源:《你不知道的JavaScript》

1.变量名提升

console.log(a) // 此时这里的a为undefined
var a = 10;

// 提升后的样子
var a;
console.log(a)
a=10;

代码在运行过程中分为编译执行两个过程,var a;是编译的一个过程,a=10;是执行的一个过程,也是就是赋值。

2.函数名提升

function show(){
    console.log('hello world')
}
show() // hello world

//以上的show方法已经提升到这段代码作用域的顶端了
show()

function show(){
    console.log('hello world')
}
//show() 原来此处的show方法已经提升了

3.函数声明和函数表达式

show() //此时的show方法会出现TypeError: show is not a function错误

var show = function(){
    console.log(123)
} 

//提升后的样子
var show;
show()

show = function(){
    console.log(123)
}

函数声明会存在提升,但是函数表达式不存在提升

4.函数优先

// 函数声明
function show(){
    console.log(123)
}

// 函数表达式
var show = function(){
    console.log('hello world')
}

// 提升函数名和变量名提升
show ()
var show

function show(){
    console.log(123)
}

show = function(){
    console.log('hello world')
}

函数名会优先提升,而变量名在之后 

要注意的是: 函数表达式是不存在函数提升的