×

javascript · level 3 · unit 2 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Private fields lock data in; getters let people peek.

Unit 1 hid data in closures. Classes have their own lock: a name starting with # is a . Only code inside the class body can touch #balance. Outside the class, even mentioning it is a SyntaxError.

A , written get balance(), runs when someone reads account.balance, so they can look but not change. Writing to it throws a TypeError in , the careful setting Gwecode always runs your code in. A method, like Account.fromPounds, belongs to the class itself.

class Account {
  #balance = 0;
  static fromPounds(pounds) {
    const account = new Account();
    account.deposit(pounds * 100);
    return account;
  }
  deposit(pence) {
    if (pence > 0) { this.#balance = this.#balance + pence; }
  }
  get balance() { return this.#balance; }
}
const savings = Account.fromPounds(12);
console.log(savings.balance, savings);

The console shows {} for savings because private fields are never printed or copied.