目錄
✅ What Is an Execution Context?
? What Is Hoisting?
Examples That Show the Difference:
? Why This Matters in Real Code
? Pro Tip: How to Avoid Hoisting Gotchas
首頁 web前端 js教程 了解JavaScript的執行上下文和提升

了解JavaScript的執行上下文和提升

Jul 25, 2025 am 02:51 AM

執行上下文是JavaScript運行代碼的環境,分為全局和函數兩種,每種都經歷創建和執行兩個階段;2. 提升是JS在創建階段將聲明(非初始化)移到作用域頂部的行為,函數聲明完全提升,var變量聲明提升但值為undefined,let/const提升但處於暫時性死區不可訪問;3. 理解這兩個概念能幫你精準調試undefined或ReferenceError問題、避免var帶來的隱式提升陷阱、並明白let/const更安全的原因。

Understanding JavaScript\'s Execution Context and Hoisting

When you start digging into how JavaScript actually runs your code — especially the weird parts like why you can call a function before declaring it — you hit two key concepts: Execution Context and Hoisting . These aren't just interview buzzwords; they explain real behavior that trips up even intermediate developers.

Understanding JavaScript's Execution Context and Hoisting

Let's break them down in plain terms.


✅ What Is an Execution Context?

Think of an execution context as the environment where your JavaScript code runs. Every time a function is called (or your script starts), JS creates a new execution context for it. There are two main types:

Understanding JavaScript's Execution Context and Hoisting
  • Global Execution Context : Created when your script first runs. Everything not inside a function lives here.
  • Function Execution Context : Created each time a function is called.

Each context has two phases:

  1. Creation Phase : JS sets up memory space for variables and functions (this is where hoisting happens).
  2. Execution Phase : JS runs your code line by line.

This two-phase setup is crucial — it's why some things seem to work “before” they should.

Understanding JavaScript's Execution Context and Hoisting

? What Is Hoisting?

Hoisting is JavaScript's behavior of moving declarations (not initializations) to the top of their scope during the creation phase.

But here's the catch:

  • Function declarations are fully hoisted — you can call them before they appear in code.
  • Variable declarations ( var , let , const ) are only partially hoisted — their declaration is moved, but not their assignment.

Examples That Show the Difference:

 console.log(myVar); // undefined (not ReferenceError!)
var myVar = 5;

console.log(myFunc()); // "Hello!" — works!
function myFunc() {
  return "Hello!";
}

console.log(myLet); // ReferenceError!
let myLet = 10;

Why the difference?

  • var myVar gets hoisted as var myVar = undefined; — so it exists but is undefined .
  • function myFunc() is fully hoisted — the whole function is available.
  • let myLet is hoisted but stays in the Temporal Dead Zone (TDZ) until the line where it's declared. Accessing it before that throws an error.

? Why This Matters in Real Code

You might not write code that calls things before declaring them (and you shouldn't!), but understanding this helps you:

  • Debug weird undefined or ReferenceError issues.
  • Avoid bugs when refactoring or working with legacy code using var .
  • Understand why let / const are safer — they don't silently default to undefined .

For example, this kind of pattern is common in older code:

 if (condition) {
  var x = 1;
} else {
  var x = 2;
}
console.log(x); // Works — but x is function-scoped, not block-scoped

With let , you'd get clearer scoping — and avoid accidental hoisting surprises.


? Pro Tip: How to Avoid Hoisting Gotchas

  • Use let and const instead of var — they're block-scoped and don't hoist in a confusing way.
  • Always declare variables at the top of their scope (especially in functions) — it makes hoisting behavior predictable.
  • Declare functions before calling them — even though JS allows it, it hurts readability.

Basically, hoisting isn't magic — it's just how JS sets up memory during the creation phase. Once you see execution context as a two-step process (setup then run), hoisting makes perfect sense.
It's not about when you write code — it's about when JS reads it.

以上是了解JavaScript的執行上下文和提升的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Laravel 教程
1602
29
PHP教程
1505
276
如何在node.js中提出HTTP請求? 如何在node.js中提出HTTP請求? Jul 13, 2025 am 02:18 AM

在Node.js中發起HTTP請求有三種常用方式:使用內置模塊、axios和node-fetch。 1.使用內置的http/https模塊無需依賴,適合基礎場景,但需手動處理數據拼接和錯誤監聽,例如用https.get()獲取數據或通過.write()發送POST請求;2.axios是基於Promise的第三方庫,語法簡潔且功能強大,支持async/await、自動JSON轉換、攔截器等,推薦用於簡化異步請求操作;3.node-fetch提供類似瀏覽器fetch的風格,基於Promise且語法簡單

JavaScript數據類型:原始與參考 JavaScript數據類型:原始與參考 Jul 13, 2025 am 02:43 AM

JavaScript的數據類型分為原始類型和引用類型。原始類型包括string、number、boolean、null、undefined和symbol,其值不可變且賦值時復制副本,因此互不影響;引用類型如對象、數組和函數存儲的是內存地址,指向同一對象的變量會相互影響。判斷類型可用typeof和instanceof,但需注意typeofnull的歷史問題。理解這兩類差異有助於編寫更穩定可靠的代碼。

過濾JavaScript中的一系列對象 過濾JavaScript中的一系列對象 Jul 12, 2025 am 03:14 AM

JavaScript中filter()方法用於創建一個包含所有通過測試元素的新數組。 1.filter()不修改原數組,而是返回符合條件元素的新數組;2.基本語法為array.filter((element)=>{returncondition;});3.可按屬性值過濾對像數組,如篩選年齡大於30的用戶;4.支持多條件篩選,例如同時滿足年齡和名字長度條件;5.可處理動態條件,將篩選參數傳入函數以實現靈活過濾;6.使用時注意必須返回布爾值,避免返回空數組,以及結合其他方法實現字符串匹配等複雜邏

如何檢查數組是否在JavaScript中包含一個值 如何檢查數組是否在JavaScript中包含一個值 Jul 13, 2025 am 02:16 AM

在JavaScript中檢查數組是否包含某個值,最常用方法是includes(),它返回布爾值,語法為array.includes(valueToFind),例如fruits.includes('banana')返回true;若需兼容舊環境,則使用indexOf(),如numbers.indexOf(20)!==-1返回true;對於對像或複雜數據,應使用some()方法進行深度比較,如users.some(user=>user.id===1)返回true。

在異步/等待JavaScript函數中處理錯誤 在異步/等待JavaScript函數中處理錯誤 Jul 12, 2025 am 03:17 AM

處理異步函數中的錯誤應使用try/catch、在調用鏈中處理、使用.catch()方法、並監聽unhandledrejection事件。 1.使用try/catch捕獲錯誤是推薦方式,結構清晰且能處理await中的異常;2.在調用鏈中處理錯誤可集中邏輯,適合多步驟流程;3.使用.catch()可在調用async函數後捕獲錯誤,適用於Promise組合場景;4.監聽unhandledrejection事件可記錄未處理的rejection,作為最後一道防線;以上方法共同確保異步錯誤被正確捕獲和處理。

如何處理JavaScript中的時區? 如何處理JavaScript中的時區? Jul 11, 2025 am 02:41 AM

處理JavaScript時區問題的關鍵在於選擇合適的方法。 1.使用原生Date對象時,推薦以UTC時間進行存儲和傳輸,並在展示時轉換為用戶本地時區;2.對於復雜時區操作,可使用moment-timezone,它支持IANA時區數據庫並提供便捷的格式化與轉換功能;3.若需本地化顯示時間且不想引入第三方庫,可使用Intl.DateTimeFormat;4.推薦現代輕量方案day.js配合timezone和utc插件,其API簡潔、性能良好並支持時區轉換。

JavaScript上下文中解釋的虛擬DOM的概念 JavaScript上下文中解釋的虛擬DOM的概念 Jul 12, 2025 am 03:09 AM

虛擬DOM是一種優化真實DOM更新的編程概念,通過在內存中創建與真實DOM對應的樹形結構,避免頻繁直接操作真實DOM。其核心原理是:1.數據變化時生成新的虛擬DOM;2.對比新舊虛擬DOM找出最小差異;3.批量更新真實DOM以減少重排重繪開銷。此外,使用唯一穩定key可提升列表對比效率,而部分現代框架已採用其他技術替代虛擬DOM。

什麼是功能編程?核心概念的JS綜述 什麼是功能編程?核心概念的JS綜述 Jul 11, 2025 am 03:13 AM

功能程序injavascriptemplosize cleansclean,precedableCodEthroughCoreConcepts.1.purefunctionsConsisterlyTurnTheSameOutTunthesMeTputputputputputputputputsefts.2.mmutability and prodicatient.2.mmutabilityabilitietyavoidsdatamodificationbybydatamodificationbybydatamodificationbybydatamodificationbybycreatingnewdatacopies,red red

See all articles