javascript / expert
Snippet
Polymorphic Event Emitter Hierarchy for Abstract React State Controllers
Demonstrates Object-Oriented Design principles using private class fields, new.target checks for abstract instantiation protection, and immutable state freezing to construct an extensible base class for React external store subscriptions.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class AbstractStateController {#listeners = new Map();constructor(initialState) {if (new.target === AbstractStateController) {throw new TypeError("Cannot instantiate abstract class directly.");}this.state = Object.freeze({ ...initialState });}subscribe(event, handler) {if (!this.#listeners.has(event)) this.#listeners.set(event, new Set());this.#listeners.get(event).add(handler);return () => this.#listeners.get(event).delete(handler);}emit(event, payload) {this.#listeners.get(event)?.forEach((fn) => fn(payload, this.state));}}
react
Breakdown
1
#listeners = new Map();
Uses private class field syntax to encapsulate event listener mappings completely from outside access.
2
if (new.target === AbstractStateController) {
Enforces abstract class semantics in JavaScript by checking if the constructor was directly invoked.
3
this.state = Object.freeze({ ...initialState });
Guarantees state immutability by performing a shallow freeze on the initial state object.
4
return () => this.#listeners.get(event).delete(handler);
Returns a cleanup closure function compatible with React useEffect subscription requirements.