DAY 28
2
Software Development

## 變數作用域

``````money = 1

def fn():
print(money) # 1

fn()
``````

``````def fn():
money = 1
print(money) # 1

fn()
print(money) # NameError: name 'money' is not defined
``````

## 閉包(Closure)

``````function count() {
let icash = 1000;
return function (price){
icash = icash - price;
return icash;
}
}
let ray = count();
ray(100); // 900
ray(200); // 700
``````

``````def count():
icash = 1000
def reduce(price):
nonlocal icash
icash = icash - price
return reduce

ray = count()
ray(100) # 900
ray(200) # 700
``````

oh！這邊你可千萬不要這樣子寫：

``````def count():
icash = 1000
return def (price):
nonlocal icash
icash = icash - price

ray = count()
ray(100) # 900
ray(200) # 700
``````

## 工廠模式

``````function myMoney(storage) {
var money = storage;
return function(price) {
return { // 使用物件函數的方式來製作功能查詢及扣除餘額
nowMoney: function () {
return console.log(money);
},
count: function (price) {
if(money < price) return console.log('餘額不足，目前餘額: ' + money + ' \$'); // 當 price 大於目前 餘額 money 就回傳錯誤。
if (!money <= 0) { // 當 money 等於 0 或是小於 money 就不進入計算。
return money = money - price;
}
return console.log('餘額扣除失敗，目前餘額: ' + money + ' \$');
}
}
}
}
// 小明比較窮只儲值 500\$
var ming = myMoney(500);
// 小美暴發戶儲值了 5000\$
var mei = myMoney(5000);
// 小王不知道哪裡來的錢，儲值了 30000\$
var wang = myMoney(30000);

// 小明連三天都花了 500\$
ming().count(100);
ming().count(100);
ming().count(300);
//查詢小明目前餘額
ming().nowMoney();
// 小美花了 2300
mei().count(1600);
mei().count(100);
mei().count(600);
//查詢小美目前餘額
mei().nowMoney();
// 小王只花 300
wang().count(300);
// 查詢小王目前餘額
wang().nowMoney();
``````

``````def myMoney(storage):
icash = storage

def nowMoney():
return print('目前餘額：', icash)

def count(price):
nonlocal icash
icash = icash - price
return print('金額扣除後剩餘：', icash)

return {
'nowMoney': nowMoney,
'count': count,
}

# 小明比較窮只儲值 500\$
ming = myMoney(500)
# 小美暴發戶儲值了 5000\$
mei = myMoney(5000)
# 小王不知道哪裡來的錢，儲值了 30000\$
wang = myMoney(30000)

# 小明連三天都花了 500\$
ming['count'](100)
ming['count'](100)
ming['count'](300)
# 查詢小明目前餘額
ming['nowMoney']()
# 小美花了 2300
mei['count'](1600)
mei['count'](100)
mei['count'](600)
# 查詢小美目前餘額
mei['nowMoney']()
# 小王只花 300
wang['count'](300)
# 查詢小王目前餘額
wang['nowMoney']()
``````