JavaScript Tutorial · Classes and Modules · Lesson 28 of 44

JavaScript Classes

Define classes with constructors, methods, getters, static members and private fields.

Defining a class

A class is a blueprint for objects. The constructor runs when you create an instance with new:

Example 1Try it yourself
class Person {
  constructor(name, birthYear) {
    this.name = name;
    this.birthYear = birthYear;
  }
  ageIn(year) {
    return year - this.birthYear;
  }
  toString() {
    return `${this.name} (born ${this.birthYear})`;
  }
}
const ada = new Person("Ada", 1815);
console.log(ada.ageIn(1843));
console.log(String(ada));
console.log(ada);

Output

28
Ada (born 1815)
Person { name: 'Ada', birthYear: 1815 }

Getters, setters and static members

  • get/set define properties computed by methods.
  • static members belong to the class itself, not to instances.
Example 2Try it yourself
class Temperature {
  static unit = "°C";
  constructor(celsius) {
    this.celsius = celsius;
  }
  get fahrenheit() {
    return this.celsius * 9 / 5 + 32;
  }
  set fahrenheit(f) {
    this.celsius = (f - 32) * 5 / 9;
  }
  static fromFahrenheit(f) {
    const t = new Temperature(0);
    t.fahrenheit = f;
    return t;
  }
}
const t = new Temperature(25);
console.log(t.fahrenheit);
console.log(Temperature.fromFahrenheit(212).celsius + Temperature.unit);

Output

77
100°C

Private fields

Fields starting with # are truly private — code outside the class can't read or change them:

Example 3Try it yourself
class BankAccount {
  #balance = 0;
  deposit(amount) {
    if (amount <= 0) throw new Error("Amount must be positive");
    this.#balance += amount;
  }
  get balance() {
    return this.#balance;
  }
}
const acct = new BankAccount();
acct.deposit(100);
console.log(acct.balance);
console.log(acct.balance === 100, Object.keys(acct));

Output

100
true []

Test yourself

Which prefix makes a class field private?

  1. _
  2. #
  3. $
  4. private_
Show answer

Answer: #

Practice next