在記憶體被釋放後, 使其變數可以繼續存活在其他作用域的方法
參考:
https://wcc723.github.io/javascript/2017/12/13/javascript-closure/
https://cythilya.github.io/2018/10/22/closure/
用閉包的概念處理setTimeout打印同步問題
for (var i = 0; i < 5; i++) {
(function(index) {
// 這個立即函示就是閉包, 在每次for迴圈執行時index變數被儲存於此, 沒有跟著被釋放掉
setTimeout(function () {
console.log(index)
}, 1000)
}(i))
}
// 依序打印0..1..2..3..4
const fn = () => {
let val = 0;
return () => val++;
};
// 將fn()記憶體存於reducer中
const reducer = fn();
reducer() // 0
reducer() // 1
reducer() // 2
fn()() // 0
參考:https://medium.com/@bebebobohaha/cookie-localstorage-sessionstorage-差異-9e1d5df3dd7f
參考:https://m.html.cn/qa/javascript/12190.htmlhttps://www.zhihu.com/question/59375764
TS優點