变量提升 Hoisting

从概念的字面意义上说,变量提升意味着变量函数声明会在物理层面移动到代码的最前面,但这么说并不准确。实际上变量函数声明在代码里的位置是不会动的,而是在编译阶段被放入内存中。

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
27
28
29
console.log(a); //=> undefined
console.log(b); //=> undefined

console.log(arr1); //=> undefined
console.log(arr2); //=> undefined

console.log(sum); //=> ƒ sum() { return 5 }

// console.log(c); //=> Uncaught ReferenceError: c is not defined (程序会出错,终止后续执行)

var a = 12;
var b = a;

var arr1 = [1, 2, 3];
var arr2 = arr1;

arr2.push(4);

function sum() {
return 5
}

console.log(a); //=> 12
console.log(b); //=> 12

console.log(arr1); //=> [1, 2, 3, 4]
console.log(arr2); //=> [1, 2, 3, 4]

console.log(sum); //=> ƒ sum() { return 5 }