js中的声明提前

简介

不多说,直接上代码

1
2
3
4
5
6
7
8
var num = 100;

function fun() {
console.log(num); //undefined
var num = 10;
console.log(num); //10
}
fun();

等价于 =>

1
2
3
4
5
6
7
8
9
var num = 100;

function fun() {
var num;
console.log(num); //undefined
num = 10;
console.log(num); //10
}
fun();

其实上面2段代码是等价的 var 声明一个变量的时候,会把它提前到改作用域的最前面。

参考

0%