Functions, Scope & Object Model

Classes, Private Fields & Methods

JavaScript classes are syntax over the prototype-based object model, with modern support for private fields and methods enforced by the runtime.
  • Class methods are prototype methods
  • Instance fields live on each object
  • #private fields are runtime-private
  • Constructors establish invariants
  • Classes still use JavaScript this rules
Class with runtime-private state
class RateLimiter {
  #remaining

  constructor(limit) {
    this.#remaining = limit
  }

  tryConsume() {
    if (this.#remaining <= 0) return false
    this.#remaining -= 1
    return true
  }
}

const limiter = new RateLimiter(2)
`#remaining` is enforced by the language runtime.
Class pieces
PieceWhere it livesNotes
constructorCalled by newInitialize instance
methodPrototypeShared by instances
public fieldInstancePer-object state
#private fieldInstance, private brandRuntime enforced
static methodConstructor functionClass-level helper
Sources
  • MDN JavaScript Guide and ReferenceUsing classes
  • ECMAScript Language SpecificationClass definitions
  • The Modern JavaScript TutorialClasses