Function
caculateAge 已存於 Global execution context
caculateAge(1998)
function caculateAge(year){
console.log(2020-year)
}
// output 22
Global execution context 只有function 宣告,變數則報錯 (Function Declaration)
caculateAge(1998);
function caculateAge(year){
console.log(2020-year);
}
retirement(1998);
var retirement = function(year){
console.log(65 - (2020 - year));
}
// output 22
// error Uncaught TypeError: retirement is not a function
variable
未宣告狀況
console.log(age)
// error Uncaught ReferenceError: age is not defined
存於 Global execution context 狀況
console.log(age)
var age = 23;
console.log(age)
// output undefined -> Global execution context
// output 22
最後是我看不懂最久的
要搭配昨天提到的執行堆疊
console.log(age)
var age = 23;
function foo(){
var age = 65;
console.log(age);
}
foo();
console.log(age);
// output undefined -> Global execution context
// 65 -> Execution context foo()
// 23 -> Global execution context
一開始真的有點難理解,age 照理說要被賦予成65,但結合昨天學到的堆疊概念,可以知道age在不同堆疊被賦予了不同的值,而執行到 foo()時,Global execution context 上被加了一層 Execution context foo(),直到 foo()執行完後被pop掉。
示意圖
Creation Phase
Global execution context (age、foo())
Execution Phase
Execution context foo() -> 執行到 foo() 時創建
Global execution context
foo()內 console.log(age) 後
Global execution context (age、foo())
其實一直都是大概理解而已,果然程式碼還是要親手打在印出來看才理解比較快
新手練功中,如有錯誤觀念,歡迎指正!
課程 : https://www.udemy.com/course/the-complete-javascript-course/