Classes — Practical Guide

Class syntax, constructor, getters/setters, static methods, extends/super, private fields (#), this binding gotchas, and common patterns (Builder, Registry, EventEmitter) — a practical companion to the desugaring article.

10 min read
JavaScript
Classes
Patterns

TABLE OF CONTENTS

JavaScript classes are the modern way to create objects with shared methods. They're used in interview questions for data structures, event systems, and custom errors. This is a practical guide to class syntax and patterns — not the desugaring to prototypes.

Related: Classes Under the Hood desugars every class feature into ES5 prototypes.


1. Basic Class Syntax

Loading editor...

Key points:

  • constructor runs once on new
  • Methods are on the prototype — shared across all instances
  • Getters/setters look like properties but run code
  • static methods are on the class itself

2. extends — Inheritance

Loading editor...

Interview use: Custom Error classes (class TimeoutError extends Error), extending EventEmitter.


3. Private Fields (ES2022)

Fields prefixed with # are truly private — not accessible outside the class:

Loading editor...

Interview use: True encapsulation in data structures (Map polyfill, LRU cache, EventEmitter).


4. this in Class Methods

Methods can lose their this context when passed as callbacks:

Loading editor...

Trade-off: Arrow-in-constructor creates a new function per instance. bind is more memory-efficient for many instances.


5. Instance vs Prototype Methods

Loading editor...


6. instanceof with Classes

Loading editor...

Interview use: Type checking in deep clone (#28) — value instanceof Date, value instanceof Map.


7. Common Patterns

Builder Pattern

Loading editor...

Registry / Factory

Loading editor...

Interview use: EventEmitter (#22) — a class with on/off/emit/once methods.


Quick Reference

FeatureSyntax
Basic classclass Name { constructor() {} method() {} }
Getterget prop() { return ... }
Setterset prop(v) { ... }
Static methodstatic method() {}
Inheritanceclass Child extends Parent { ... }
super callsuper(args) in constructor
super methodsuper.method()
Private field#field
Private method#method() {}
instanceofobj instanceof Class

Interview Tips

  • Call super() before this — in a derived class constructor, this doesn't exist until super() runs.
  • Use private fields for true encapsulation — the # prefix is real privacy, not convention.
  • Bind methods or use arrow fields — if the method will be passed as a callback.
  • Use instanceof for type-safe error handlingcatch (err) { if (err instanceof TimeoutError) ... }.

Related Articles


Let's Connect

© 2026 Naveen Karthik // Built with React & MUI