JavaScript 引擎負責讓瀏覽器或 Node.js 看懂並執行 JS 程式碼。
任何 JS 程式碼在執行時,都有對應的執行環境。
全域執行環境(Global Execution Context)
函式執行環境(Functional Execution Context)
Eval 執行環境
JS 採「後進先出(LIFO)」的堆疊結構:
function enterCastle() {
return floorOne();
}
function floorOne() {
return floorTwo();
}
function floorTwo() {
return "任務完成,取得寶藏!";
}
let result = enterCastle();
console.log(result);
函式呼叫順序:
作用域(Scope)又稱「範疇」,代表變數可被存取的範圍。
Hoisting:
JS 執行環境會分成兩個階段:
建立階段(Memory Creation Phase)
執行階段(Execution Phase)
一般函式(function 關鍵字宣告)整個內容會被提升,
而變數只提升「宣告」,不提升「賦值」。
類型 | 特性 |
---|---|
Stack(堆疊) | 儲存執行時的函式呼叫與基本型別 |
Heap(堆積) | 儲存物件與動態資料 |
JS中 | 變數的宣告與內容會依型別分別存於 Stack 或 Heap |
function exampleVar(){
var x = 1;
if (true){
var x = 2; // 同一個變數
console.log(x); // 2
}
console.log(x); // 2
}
Hoisting 範例:
console.log(greeter); // undefined
var greeter = "say hello";
// 實際上等同於:
var greeter;
console.log(greeter);
greeter = "say hello";
function exampleLet(){
let x = 1;
if (true){
let x = 2; // 不同變數
console.log(x); // 2
}
console.log(x); // 1
}
function exampleConst(){
const x = 1;
if (true){
const x = 2; // 不同變數
console.log(x); // 2
}
console.log(x); // 1
}
重複宣告會出錯:
function exampleLet(){
let x = 1;
let x = 2; // SyntaxError
}
宣告前使用:
console.log(y); // ReferenceError
let y = 5;
3. var vs let 的差異(for loop 範例)
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
// 3, 3, 3
for (let j = 0; j < 3; j++) {
setTimeout(() => console.log(j), 100);
}
// 0, 1, 2
const → 預設選擇
let → 需要修改變數時
var → 避免使用