front-end-interview-handbook/packages/quiz/questions/explain-hoisting/zh-CN.mdx

44 lines
1.5 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: 解释“(变量)提升”
---
提升是用于解释你代码中变量声明行为的一个术语。 使用`var`关键字声明或初始化的变量将会将其声明“移动”到其模块/函数级别范围的顶端。 我们把它成为变量提升。 然而,只有声明被提升,赋值(如果有的话)将留在原地。
请注意,声明实际上并没有被移动--JavaScript引擎在编译过程中解析了声明并意识到了声明及其作用域。 通过视觉将声明置于其作用域之首,更容易理解这种行为。 让我们用几个例子来解释。
```js
console.log(foo); // undefined
var foo = 1;
console.log(foo); // 1
```
函数声明的主体提升到顶端,而函数表达式(以变量声明的形式写成) 只有变量声明被提升到顶端。
```js
// Function Declaration
console.log(foo); // [Function: foo]
foo(); // 'FOOOOO'
function foo() {
console.log('FOOOOO');
}
console.log(foo); // [Function: foo]
// Function Expression
console.log(bar); // undefined
bar(); // Uncaught TypeError: bar is not a function
var bar = function () {
console.log('BARRRR');
};
console.log(bar); // [Function: bar]
```
通过 `let` 和 `const` 声明的变量也被提升。 然而,与`var` 和 `function`不同的是,在声明导致`ReferenceError` 例外之前,它们没有初始化并访问它们。 该变量处于从代码块开始直到声明被处理时的一个“暂时性死区”。
```js
x; // undefined
y; // Reference error: y is not defined
var x = 'local';
let y = 'local';
```