Skip to the page

Objects, prototypes and classes · mid

Classes: fields, #private, static and super

A class is a special constructor with a strict-mode body, methods on the prototype, per-instance fields, real privacy with #names, static members on the class itself and super for calling the parent — more than syntax sugar.

The notes

What you must know

  • Differences from constructor functions: the body is strict; class declarations are in the TDZ until defined; calling without new throws; methods are non-enumerable; extends links both the instance chain and the static chain.
  • Fields (x = 1) are created on each instance; in a derived class they are added right after super() returns. Methods live on the prototype.
  • #private fields and methods are enforced by the engine. #x in obj is a brand check. They are invisible to Object.keys, JSON.stringify and Proxy.
  • A derived constructor must call super() before using this, otherwise ReferenceError.
  • static methods and fields live on the class; static { } blocks run setup once; this inside a static method is the class.
  • TypeScript private is erased at compile time; #private exists at runtime.
  • Trap: if a base constructor calls a method that the child overrides, the child's fields are not initialised yet at that moment.

The red pen

Common traps: mistake → fix

  • Mistake: Classes are just sugar

    Fix: strict mode, TDZ, new-only calls, non-enumerable methods, super and #private are real differences.

  • Mistake: TypeScript private is private at runtime

    Fix: it is erased; use #private.

  • Mistake: Fields live on the prototype

    Fix: fields are per instance; methods are on the prototype.

Easy to hard

Questions interviewers ask, easy to hard

  1. ES classes vs ES5 constructor functions: what is really different?
  2. What are class fields and #private? How is #private different from TypeScript private?
  3. Why must you call super() before using this?
  4. When are static members and static blocks useful?
  5. Explain the base-constructor-calls-overridden-method field initialisation trap.

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview