JavaScript 執行環境 Execution context

執行環境 Execution context

傅勝華
Jul 8, 2021

創造階段 Creation Phase

這個階段會先為變數和函數騰出記憶體,變數會被設定成 undefined 直到下階段才會被真正設定。
P.S. : error… is not defined 意思是記憶體裡沒這個變數, undefined 是 JS 的特殊字眼,意思是尚未設定,因此變數盡量不要設定成 undefined ,否則無法辨別是你設定的還是機器設定的。

執行階段 Execution Phase

這個階段會開始一行一行讀取程式碼。

練習:two phase of execution context

執行堆 Execution Stack

JavaScript 是 單執行緒 Single Thread and 同步性 Synchronous
意思是 JS 每次只會執行一個程序,而且是一行一行讀取

練習:stack and scope chain

variable environment

以上面的例子來說變數 value 共有 3 個,每一個所在的執行環境都不一樣,創造出來的時間點也不一樣。

scope chain

當 b 函數裏頭沒有 value 會從 outer environment 去尋找變數
outer environment 有兩種判斷方式--
一:函數的 詞彙環境 Lexical Environment (放在哪裡);
二:函數是何時被創造出來放入記憶體,創造它的的 Execution Context 就是它的 外部環境 outer environment。

練習:stack and scope chain & stack and scope chain b() in a()

非同步 Asynchronous

JS 本身是同步性的程式語言,非同步只是一個假象,實際上是先放到一旁,等 Execution Stack 都執行完,才會把第一個 事件貯列Event Queue 放到Execution Stack 執行,再執行下一個,以此類推。

Ref
[JavaScript] Javascript 的執行環境 (Execution context) 與堆疊 (Stack)
JavaScript 全攻略:克服 JS 的奇怪部分

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

傅勝華
傅勝華