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
#privatefields are runtime-private- Constructors establish invariants
- Classes still use JavaScript
thisrules
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)| Piece | Where it lives | Notes |
|---|---|---|
| constructor | Called by new | Initialize instance |
| method | Prototype | Shared by instances |
| public field | Instance | Per-object state |
| #private field | Instance, private brand | Runtime enforced |
| static method | Constructor function | Class-level helper |