呼叫堆疊就是儲存函式呼叫順序的背景環境的一種資料結構,基本上跟 data structure 內 **stack **運作模式相同(store the order of function calls)
依循 last-in first-out 的特性,像疊盤子,新來的盤子疊在最頂端,取盤子也是先從頂端先取走
function first(){
second();
}
function second(){
...
}
first();
call stack 會長這樣
執行 first 將 first 加到 call stack
執行 second 將 second 加到 call stack
second 被執行完畢 從 call stack移除
first 被執行完畢 從 call stack移除
first-in, first-out 像排隊,先來的人先離開,後來的排在先來的人之後
閉包是一種特定的巢狀函式實例,閉包必定為巢狀函式(all closures are nested functions)
其結構為外層函式包含內層函式,其內層函式可以記憶並存取外部範圍的變數(inner function can remembers and accesss variables from its outter scope)
另外雖然 setTimeout 跟 setInterval 也是函式包著函式的型態,但它們並非閉包
並不是所有巢狀函式都是閉包
closure 有幾種常見用途
function createCounter(){
let count = 0; // This variable is "private"
return {
increment: function (value) {
count = count += value;
return count;
},
decrement: function (value) {
count = count -= value;
return count;
},
getCount: () => {
return count;
},
};
}
const count1 = createCounter();
count1.increment(12);
console.log(count1.getCount()); // 12
const count2 = createCounter();
count2.increment(18);
count2.decrement(5);
console.log(count2.getCount()); // 13
function textColorChangeMaker(className, hexColor) {
return function () {
let allElements = document.querySelectorAll(`.${className}`);
allElements.forEach((elm) => (elm.style.color = `${hexColor}`));
};
}
const sloganColorChange = textColorChangeMaker("slogan", "#ffdd00");
const contentColorChange = textColorChangeMaker("content", "#c222cc");
document
.getElementById("colorChangeBtn")
.addEventListener("click", () => {
sloganColorChange();
contentColorChange();
});