Skip to content

Hoisting

一句话解释

Hoisting 是 JavaScript's behavior 的 moving 变量 and 函数 declarations 到 顶部 的 它们的 作用域 之前 code execution.

用大白话说

Hoisting means JavaScript processes declarations before executing the code. It is as if variable and function declarations are "hoisted" (lifted) to the top of their scope.

var declarations are hoisted and initialized to undefined — you can use the variable before its declaration line (it will be undefined). Function declarations are fully hoisted — both the name and the function body, so you can call them before they appear in the code.

let and const are hoisted but NOT initialized — they exist in the "temporal dead 区域" (TDZ) until their declaration line. Accessing them before the line throws a ReferenceError. Only the declaration is hoisted, not the assignment.

示例

javascript
console.log(greet()); // "Hi" — function declaration hoisted
function greet() { return "Hi"; }

console.log(x); // undefined — var hoisted
var x = 5;

函数 declarations 是 fully hoisted. var 是 hoisted and initialized 到 undefined.

常见混淆

  • 容易混淆的对象: temporal dead 区域

    关键区别: Hoisting moves declaration 到 顶部; TDZ 是 period 之间 hoisting and initialization 哪里 let/const 变量 exist 但 cannot 是 accessed.

相关术语

相关资源

相关课程

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表