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:
constructorruns once onnew- Methods are on the prototype — shared across all instances
- Getters/setters look like properties but run code
staticmethods 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
| Feature | Syntax |
|---|---|
| Basic class | class Name { constructor() {} method() {} } |
| Getter | get prop() { return ... } |
| Setter | set prop(v) { ... } |
| Static method | static method() {} |
| Inheritance | class Child extends Parent { ... } |
super call | super(args) in constructor |
super method | super.method() |
| Private field | #field |
| Private method | #method() {} |
| instanceof | obj instanceof Class |
Interview Tips
- Call
super()beforethis— in a derived class constructor,thisdoesn't exist untilsuper()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
instanceoffor type-safe error handling —catch (err) { if (err instanceof TimeoutError) ... }.