Skip to content

Chapter 16 of 33

Classes

Use constructors, inheritance, accessors, private fields, static members, and composition.

40 minutes 10 quick checksBy Subha Prasad
Lesson 16 of 33Course navigation

Lesson content

Read, practise, then check your understanding

Classes provide strict prototype-based constructor syntax. Methods live on the prototype; fields initialize per instance.

Encapsulated model

class Account {
  #balance = 0;
  constructor(owner) { this.owner = owner; }
  deposit(amount) {
    if (amount <= 0) throw new RangeError("positive amount required");
    this.#balance += amount;
  }
  get balance() { return this.#balance; }
  static from(data) { return new Account(data.owner); }
}

extends and super build inheritance, while # fields enforce privacy. Methods lose their receiver when passed bare, so bind or wrap callbacks. Prefer composition for reusable capabilities and inheritance only for genuine substitutability. Constructors cannot be async; use an async factory when setup requires awaiting.

Knowledge check

Answer every question correctly to complete this chapter.

Which statement best describes class?
Which JavaScript term matches this description: Prototype-based constructor and method syntax with strict semantics.
Which statement best describes constructor?
Which JavaScript term matches this description: The special method initializing instances created with new.
Which statement best describes extends?
Which JavaScript term matches this description: Syntax linking derived and base constructor prototypes.
Which statement best describes private field?
Which JavaScript term matches this description: A class element named with # and enforced by the language.
Which statement best describes static member?
Which JavaScript term matches this description: A member stored on the class constructor rather than instances.

0 of 10 checks passed

Your progress is saved on this device.