DAY 20
0
Modern Web

## Day 20 閉包

，在函數被加進執行堆上方，

``````function greet(whattosay) {

return function(name) {
console.log(whattosay + ' ' + name);
}

}

greet('Hi')('Jimmy');
``````

``````function greet(whattosay) {

return function(name) {
console.log(whattosay + ' ' + name);
}

}

var sayHi = greet('Hi');
sayHi('Jimmy');
``````

``````var sayHi = greet('Hi');
``````

``````console.log(whattosay + ' ' + name);
``````

``````function buildFunctions() {
var arr = [];

for(var i = 0; i < 3; i++) {
arr.push(function() {
console.log(i);
});
}

return arr;
}

fs = buildFunctions();

fs[0]();
fs[1]();
fs[2]();
``````

for 迴圈因為條件的關係，最後將變數 i 設值成 3，

「如果問同個爸爸生的不同年齡的小孩爸爸年齡幾歲？他們不會因為年齡不同，在回答時回答不一樣的答案」。

``````function buildFunctions2() {
var arr = [];

for(var i = 0; i < 3; i++) {
let j = i;
arr.push(function() {
console.log(j);
});
}

return arr;
}

fs2 = buildFunctions2();

fs2[0]();
fs2[1]();
fs2[2]();
``````

``````function buildFunctions2() {
var arr = [];

for(var i = 0; i < 3; i++) {
arr.push((function(j) {
return function() {
console.log(j);
}
}(i)));
}

return arr;
}

fs2 = buildFunctions2();

fs2[0]();
fs2[1]();
fs2[2]();
``````

Console 中的結果如下：