JavaScript变量提升

JavaScript 中,函数及变量的声明都将被提升到函数的最顶部。

1
2
3
4
5
6
7
8
9
10
11
a = 2;
console.log(a); //2

var a;

foo();
function foo() {
// 每个作用域都会进行提升操作
console.log(b); // undefined
var b = 2;
}

以上代码段会被引擎理解为如下形式:

1
2
3
4
5
6
7
8
9
10
11
12
function foo() {
var b;
console.log(b); // undefined
b = 2;
}

var a;

a = 2;
console.log(a); //2

foo();

函数声明和变量声明都会被提升。但是一个值得注意的细节是函数会首先被提升,然后才是变量

1
2
3
4
5
6
7
8
9
10
11
12
foo(); // 3
var foo;
function foo() {
console.log(1);
}
foo = function() {
console.log(2);
};

function foo() {
console.log(3);
}

var foo 尽管出现在 function foo()… 的声明之前,但它是重复的 var 声明被忽
略了,但是出现在后面的函数声明还是可以覆盖前面的,所以输出 3

注意:es6 中 let 和 class 不存在变量提升的现象

1
2
3
4
a = 1; // ReferenceError: a is not defined
console.log(a);

let a;
1
2
3
const a = new A(); // ReferenceError: A is not defined

class A {}