JS变量提升

  • js并不是一行一行向下执行的
  • js执行分成两个步骤:
    • 编译(词法解释/预解释)
    • 执行
1
2
3
4
5
6
7
8
9

a = 'ghostwu';
var a;
console.log( a );
//上面这段代码经过编译之后,变成下面这样

var a; //被提升到当前作用域的最前面
a = 'ghostwu'; //留在原地,等待执行
console.log( a );

函数声明会被提升

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
show()
function show(){
console.log(a);
var a = 'test';
}

// 上面的代码经过编译之后会变成这样

function show(){
var a;
console.log(a);
a = 'test';
}

show() // undefined

而函数表达式不会被提升

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

show() // 报错,show is not a function

var show = function(){
console.log(a);
var a = 'test';
}

// 编译后

var show

show()

show = function(){
var a
console.log(a)
a = 'test'
}

当出现同名的函数声明、变量声明的时候,函数声明的优先级会被提升,变量声明会被忽略。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
show() // 你好
function show(){
console.log('你好')
}
var show

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

// 编译后

function show(){
console.log('你好')
}

show()

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

如果有同名的函数声明,后面的会覆盖前面的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
show() // how are you
var show

function show(){
console.log('你好')
}

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

function show(){
console.log('how are you')
}

// 编译后

function show(){
console.log('how are you')
}

show()

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

https://www.cnblogs.com/ghostwu/p/7287189.html