JavaScript · Level 3 OOP

Classes and #private Fields

Build a JavaScript class whose data is hidden in a #private field and read through getters and setters that look like plain properties.

  • class, constructor and methods
  • get and set accessors
  • #private fields

A get/set pair runs code but reads like a property. Fields starting with # are truly private: obj.#secret outside the class is a SyntaxError, and they never show up in Object.keys.

class Account {
  #balance = 0;
  deposit(n) { this.#balance += n; }
  get balance() { return this.#balance; }
}

const acc = new Account();
acc.deposit(50);
acc.balance;   // 50

Write class Temperature that stores its constructor value in #celsius, with a celsius getter and a fahrenheit getter and setter (F = C * 9 / 5 + 32), e.g. new Temperature(100).fahrenheit is 212.

solution.js
Test Suites Pending
Output