即使函式已經執行結束,其內部的變數卻並未跟著消除,還能繼續被呼叫;這種能將外層變數「包」在內層暫存、使用的方式,就是所謂的「閉包」。
執行環境(Execution Context,EC) 指的是 Javascript 底層在程式準備執行時,所建立的一個物件,主要是儲存了:

(圖片來源:參考)
function storeMoney () {
    var money = 1000;
    return function(price) {
        money = money + price;
        return money;
    }
}
console.log(storeMoney()(100));
回傳:1100
function storeMoney(initValue) {
    var money = initValue || 1000;
    return {
        increase: function (price) {
            money += price;
        },
        decrease: function (price) {
            money -= price;
        },
        value: function () {
            return money;
        }
    }
}
var MingMoney = storeMoney(100);
MingMoney.increase(100);
MingMoney.increase(100);
MingMoney.increase(100);
MingMoney.increase(100);
MingMoney.decrease(25);
MingMoney.decrease(96);
comsole.log(MingMoney.value());
回傳:379 , 2000