Example 1 — Private State
Hide a value so only the returned functions can change it.
function bank(start) {
let balance = start;
return {
deposit(n) { balance += n; return balance; },
get() { return balance; }
};
}
const acct = bank(100);
console.log(acct.deposit(40));
console.log(acct.get()); How It Works
- Hidden balance. Nothing outside can touch
balancedirectly. - Methods close over it.
depositandgetshare the same variable.
