1. var、let、const 的差异?
相同:
var let const都是用来进行变量声明。
不同:
(1)var声明的变量会添加到全局对象中,可以使用全局对象进行访问,let和const则不会。
(2)var声明的变量存在变量提升,可以在声明前就行访问,不会报错。而let和const声明的变量存在暂时性死区,不可以提前访问。
(3)let和const是块级作用域,不可以在一个作用域内重复声明。var是函数作用域,可以重复声明
(4)const声明的常量不可以修改,如果是引用类型不可以修改指针也就是重新赋值。
2. 变量提升
例1
function hoistVariable() {
if (!foo) {
var foo = 5;
}
console.log(foo); // 5
}
hoistVariable();
预编译后
// 预编译之后
function hoistVariable() {
var foo;
if (!foo) {
foo = 5;
}
console.log(foo); // 5
}
hoistVariable();
3. 函数提升
例1
function hoistFunction() {
foo(); // output: I am hoisted
function foo() {
console.log('I am hoisted');
}
}
hoistFunction();
预编译后
// 预编译之后
function hoistFunction() {
function foo() {
console.log('I am hoisted');
}
foo(); // output: I am hoisted
}
hoistFunction();
例2
function hoistFunction() {
foo(); // 2
var foo = function() {
console.log(1);
};
foo(); // 1
function foo() {
console.log(2);
}
foo(); // 1
}
hoistFunction();
预编译后
// 预编译之后
function hoistFunction() {
var foo;
foo = function foo() {
console.log(2);
}
foo(); // 2
foo = function() {
console.log(1);
};
foo(); // 1
foo(); // 1
}
hoistFunction();
例3
var foo = 3;
function hoistFunction() {
console.log(foo); // function foo() {}
foo = 5;
console.log(foo); // 5
function foo() {}
}
hoistFunction();
console.log(foo); // 3
预编译后
// 预编译之后
var foo = 3;
function hoistFunction() {
var foo;
foo = function foo() {};
console.log(foo); // function foo() {}
foo = 5;
console.log(foo); // 5
}
hoistFunction();
console.log(foo); // 3