Closure
限制變數在儲存環境的作用範圍
利用變數作用域的特性,加上一層function
避免污染global環境
變數不會在function執行完畢後消失
會保留結果至下次執行
code:without closure(javascript)
// without closure
var count = 0;
function counterTick() {
return ++count;
}
console.log(counterTick()); // 1
console.log(counterTick()); // 2
code:with closure(javascript)
// with closure
function counter() {
var count = 0;
function counterTick() {
return ++count;
}
return counterTick;
// also could be written as arrow function
// return () => ++count;
}
var countFunc = counter();
console.log(countFunc()); // 1
console.log(countFunc()); // 2
code:javascript
const a = [];
{
for (let i = 0; i < 10; i++) {
ai = () => console.log(i); }
}
{
let i;
for (i = 0; i < 10; i++) {
ai = () => console.log(i); }
}
{
for (let i = 0; i < 10; ) {
ai = () => console.log(i); i++;
}
}