# JavaScript－－閉包

eg1:

``````function sum(arr) {
var sum = function () {//在sum()函數內部定義了新函數
return arr. reduce(function (x,y){
return x + y;//新函數引用了sum的局部變量，並保存起來
});
}
return sum;
}
var sum1 = sum([1,2,3]);
var sum2 = sum([1,2,3]);
sum1();//6
sum1 === sum2;//false``````

eg2:

``````function fun() {
var arr = [];
for (var i = 1;i <= 3;i ++){
arr.push(function (){//數組裏面push進去的是函數
return i*i;//for的每次循環都會創建一個函數放進arr裏面
});
}
return arr;//返回結果的時候，數組裏面的每個元素都是i*i，此時i＝4；
}
var f1 = answer[0];//執行函數f1() = 16
var f2 = answer[1];//f2() = 16
var f3 = answer[2];//f3() = 16``````

eg3:

``````(function (x) {
return x*x;
})(2);``````

``````function count() {
var arr = [];
for (var i=1; i<=3; i++) {
arr.push((function (n) {
return function () {
return n * n;
}
})(i));
}
return arr;
}
var results = count();
var f1 = results[0];//執行f1() = 1
var f2 = results[1];//f2() = 4
var f3 = results[2];//f3() = 9``````

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

eg4:

``````function count(num) {
var x = num || 0;
return {//返回一個對象
privateProperty : function  () {
x += 1;
return x;
}
}
}
var m1 = count();//0
m1.privateProperty();//1
m1.privateProperty();//2
var m2 = count(2);//2
m2.privateProperty();//3
m2.privateProperty();//4``````