function newAccount ()
--保存對象狀態(tài)的table保存在閉包環(huán)境下
local self = {balance = initialBalance}
local withdraw = function (v)
self.balance = self.balance - v
end
local deposit = function (v)
self.balance = self.balance + v
end
local getBalance = function () return self.balance end
return {
withdraw = withdraw,
deposit = deposit,
getBalance = getBalance
}
end
acc1 = newAccount(100.00)
acc1.withdraw(40.00)
print(acc1.getBalance()) --> 60
一. 單方法(The Single-Method Approach)
適用于當(dāng)對象只有一個方法時使用
使用閉包笨奠,性能比table更好
同樣實(shí)現(xiàn)了Privacy功能
function newObject (value)
return function (action, v)
if action == "get" then return value
elseif action == "set" then value = v
else error("invalid action")
end
end
end
d = newObject(0)
print(d("get")) --> 0
d("set", 10)
print(d("get")) --> 10