Constructors और Instance State
एक constructor function एक object बनाता है और हर instance को अपना data देता है।
In this page:
Constructors और Instance State
एक constructor आमतौर पर new नाम का एक function है जो एक table बनाता है, class metatable attach करता है और इसे return करता है। हर object अपने fields store करता है, इसलिए एक बदलना दूसरों पर असर नहीं डालता। खुद class में रखा data सारे instances से share होता है, और एक instance के जरिए assign करना एक private field बनाता है जो इसे shadow करता है।
Note:
per-object data self पर store करें और constants या counters class पर।
उदाहरण: Constructors and instance state
local Account = {count = 0}
Account.__index = Account
function Account.new(owner, balance)
local self = setmetatable({}, Account)
self.owner = owner
self.balance = balance or 0
Account.count = Account.count + 1
return self
end
function Account:deposit(n) self.balance = self.balance + n end
local a, b = Account.new("Ann", 100), Account.new("Bob")
a:deposit(50)
print(a.balance, b.balance, Account.count)
a.count = 99
print(a.count, b.count)
-- Output:
-- 150 0 2
-- 99 2
Login to try C/C++/Java/PHP code in the editor
आम गलतियां
- mutable per-object data class table में रखना
- new से object return करना भूल जाना
- यह उम्मीद करना कि एक instance पर assignment एक shared class field बदल देगी
चैप्टर सारांश
- new instance बनाता और return करता है
- Instance fields इसके लिए private हैं
- Class fields shared हैं
- एक instance पर assign करना एक class field shadow करता है
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: