Glossary / Classes

Classes

JavaScript classes provide syntax for constructors, instance fields, methods, inheritance, static members, and private elements. They are built on prototypes rather than a separate class-based object model. Compared with old constructor functions, class bodies are strict, class constructors require new, and methods are non-enumerable prototype properties.

Fields, methods, and initialization

class Account {
  #balance = 0;
  constructor(owner) { this.owner = owner; }
  deposit(amount) { this.#balance += amount; }
  get balance() { return this.#balance; }
  static fromRecord(record) { return new Account(record.owner); }
}

Public instance fields are created per instance; prototype methods are shared. Static members belong to the constructor. Private names beginning with # are language-enforced elements, not string-keyed properties. Class declarations have a temporal dead zone; class expressions can be named or anonymous. Field initialization order and base/derived constructor ordering matter, especially when overriding methods called from constructors.

Classes do not automatically enforce invariants: public fields can be written freely unless accessors/private state constrain them. Inheritance can couple classes through initialization and override behavior. Prefer composition when capabilities can be assembled independently. Avoid class hierarchies created solely to share a few utility functions.

Reflection and compatibility

Prototype relationships still determine instanceof and inherited method lookup. Serialization does not automatically preserve a class prototype; parsed JSON is not an instance of the original class. Transpilation may change how private fields and inheritance are implemented, so check target support and emitted semantics.

Interview questions

  1. Are classes separate from prototypes? No, class instances still use prototype chains.
  2. Where do instance methods live? On the class prototype, unless defined as instance fields (which allocate per instance).
  3. Do class fields make state private? No; only #private elements are inaccessible through ordinary property access.
  4. Does JSON preserve a class instance? No; it serializes data and parsing does not restore the prototype.

References