# JS 变量提升和函数提升的顺序
# 1.变量的提升:
变量名会提升到 ‘当前作用域’ 顶部,此时该变量为 undefined,未赋值,赋值是在 js 原位置。
console.log(a); // undefined
var a = 10;
console.log(a); // 10
1
2
3
2
3
在 js 解析之后:
var a;
console.log(a); // undefined
a = 10;
console.log(a); //10
1
2
3
4
2
3
4
# 2.函数的提升
# 函数的类别:
- 函数声明:function a( ){ };
- 函数表达式:var a = function( ){ };
- 匿名函数:function( ){ };
- 立即执行函数:(function(str){ })(str)
TIP
其中: 函数声明存在函数提升 函数表达式等价于变量提升
a();
function a() {
console.log("a");
}
1
2
3
4
5
2
3
4
5
在解析之后相当于
function a() {
console.log("a");
}
a(); // "a"
1
2
3
4
2
3
4
# 3.变量提升和函数提升优先级:
- 函数提升优先级高于变量提升
- 当函数声明与变量名相同时,在变量赋值前,函数声明依旧是函数声明,不会被覆盖;当变量赋值后,函数声明被同变量覆盖。
console.log(a); // ƒ a(){ console.log("函数a"); }
function a() {
console.log("函数a");
}
a(); // '函数a'
var a = "变量a";
console.log(a); // '变量a'
a(); // a is not a function
// 输出结果及顺序:
// ƒ a(){ console.log("函数a"); }
// '函数a'
// '变量a'
// a is not a function
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
函数解析之后相当于:
function a() {
console.log("函数a");
}
var a;
console.log(a); // ƒ a(){ console.log("函数a"); }
a(); // '函数a'
a = "变量a"; // 此时变量a赋值,函数声明被覆盖
console.log(a); // "变量a"
a(); // a is not a function
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12