Sikau

Advanced JavaScript · Day 7 · about 30 min

Class features

Static, private fields, getters and setters.

Classes, fully loaded

Classes are tidy syntax over prototypes. Modern classes add powerful extras: truly private fields, computed getters, validating setters, and static helpers that belong to the class itself.

Private fields and static members

class BankAccount {
  static #count = 0;
  #balance = 0;

  constructor(owner) {
    this.owner = owner;
    BankAccount.#count++;
  }
  deposit(n) {
    this.#balance += n;
  }
  get balance() {
    return this.#balance;
  }
  static howMany() {
    return BankAccount.#count;
  }
}

const a = new BankAccount("Gita");
a.deposit(300);
console.log(a.balance);
console.log(BankAccount.howMany());
console.log(Object.keys(a));

The rest of this lesson

  • Setters that validateexplain
  • Designing a class's public faceexplain
  • Predict the outputpredict
  • Class featuresmatch
  • Your turnwrite code
  • Challengechallenge
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 27 lessons of Advanced JavaScript