๐กprivate property by closure
JS โฉ value โฉ function โฉ closure โฉ private property by closure
replit๏ผclosure: private property
'use strict'; // โญ toggle sloppy/strict mode
const { log } = console;
// bank account
function BankAccount(initialBalance = 0) {
// โญ initial balance
let balance = initialBalance;
// โญ return an object
return {
getBalance() {
return balance
},
deposit(amount) {
balance += amount;
return balance;
},
withdraw(amount) {
// check if we have enough money to withdraw.
if (amount > balance) {
log(`โ balance: $${balance} less than withdraw amount: $${amount}.`);
return false; // withdraw failed
}
balance -= amount;
return true; // withdraw successful
}
}
}
const myAccount = BankAccount(100); // initial balance = 100
// log
[
myAccount.deposit(10), // 110
myAccount.withdraw(80), // true (successful)
myAccount.getBalance(), // 30
myAccount.withdraw(80), // false (failed)
// โ balance (30) is less then withdraw amount (80).
myAccount.getBalance(), // 39
].forEach(x => log(x));
replit๏ผprivate property by closure (2)
// Counter
function Counter() {
// โญ๏ธ private property in closure
let count = 0;
// โญ๏ธ (method) function closes over `count`
this.up = function() {
return ++count;
};
this.down = function() {
return --count;
};
}
// an instance of Counter
let counter = new Counter();
counter.up(), // 1
counter.up(), // 2
counter.down(), // 1
Last updated