All posts
postApril 6, 2026

WeakMap for Private Data

#javascript#weakmap#oop#memory
WeakMap for Private Data — slide 1
javascript
const _private = new WeakMap();

class BankAccount {
  constructor(balance) {
    _private.set(this, { balance });
  }
  deposit(amount) {
    const data = _private.get(this);
    data.balance += amount;
  }
  get balance() {
    return _private.get(this).balance;
  }
}

const acc = new BankAccount(100);
acc.deposit(50);
console.log(acc.balance);  // 150
// acc._private → undefined (truly private)