According to the ECMAScript specification, this behavior is actually part of the creation of the so -called "lexical environment" in the creation stage of JavaScript. But let us not be too technical, just remember that JavaScript will "scan" it before running the code.
improvement
var
console.log(x); // 输出:undefined var x = 5; console.log(x); // 输出:5
has not been improved. This is why the first <出> output var x
instead of throwing an error. Variables <存> exist, but it has not been assigned. x = 5
console.log(x)
<<> and undefined
The temporary dead area (TDZ) x
let
statement was improved, but it was located in a temporary dead area (TDZ) before initialization. Try to access const
before initialization will lead to console.log(y); // 抛出ReferenceError: Cannot access 'y' before initialization let y = 10; console.log(y); // 输出:10
in similar circumstances. let y
y
ReferenceError
This also includes any content using <这> or var
declaration, of course, also includes functions. var
undefined
before the initial access, these modern statements will be misunderstood. The ECMAScript specification refers to this behavior as "temporary dead region semantics", but I call it "JavaScript makes us honest."Speaking of temporary dead areas, this is where
returnslet
andconst
declare before the initialization. Different from <始> when
let
const
What happened to see here? Functional declaration <提> has been improved, so we can call it in advance. But what about <呢>? It still stays in its place. This is why <部> visit var
will give us undefined
, and we try to read it before the script is ready.
function setupEventHandler() { handleClick(); // 可运行! const config = { debug: true, }; function handleClick() { if (config?.debug) { // 未定义! console.log("Debug mode"); } } } setupEventHandler();
handleClick
config
Although the class is improved, they are still in the "temporary dead zone" before their definitions are evaluated. This means that you cannot access them before you declare them. handleClick
config
undefined
Remember, the statement was moved to the top, but the initialization remained unchanged.
The above is the detailed content of Javascript Hoisting - What Moves and What Stays. For more information, please follow other related articles on the PHP Chinese website!