Decorator Pattern Implementation in JavaScript
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Decorator Pattern runs in O(1) time and O(n) space, in JavaScript as in every other language.
- ✓There is no decorator type; the pattern is expressed with higher-order functions for behaviour and with Proxy for transparent object wrapping.
- ✓Use a higher-order function when you are wrapping a FUNCTION, and Proxy only when you must intercept arbitrary property access on an object you do not control.
- ✓The JavaScript trap: Proxy enforces INVARIANTS and throws when you violate them: if the target has a non-configurable, non-writable property, your get trap must return exactly that value or the engine throws a TypeError at access time, so a logging proxy over a frozen object crashes in production and not in your test against a plain object.
- ✓Proxy is substantially slower than direct property access and, more importantly, it prevents V8 from using inline caches and hidden-class optimisations for the wrapped object, so the cost is not a fixed overhead but a deoptimisation of everything downstream.
What Decorator Pattern actually is
Decorator Pattern in JavaScript: what you actually reach for
JavaScript implementation
// Function decoration: a higher-order function, no magic needed.
const withTiming = (fn) =>
async function (...args) {
const t0 = performance.now();
try { return await fn.apply(this, args); } // forward the receiver
finally { console.log(fn.name, performance.now() - t0); }
};
// Object decoration: Proxy, and ALWAYS delegate through Reflect.
function countReads(target) {
let reads = 0;
return new Proxy(target, {
get(t, prop, receiver) {
reads++;
// Reflect passes the receiver so getters and prototypes behave.
return Reflect.get(t, prop, receiver);
},
has(t, prop) { return Reflect.has(t, prop); },
});
}
// Proxy INVARIANTS throw at runtime: over a frozen object, a get trap
// that returns anything but the exact value is a TypeError.
const frozen = Object.freeze({ a: 1 });
const bad = new Proxy(frozen, { get: () => 'nope' });
// bad.a -> TypeError: proxy must report the same value for a
// non-writable, non-configurable property
export { withTiming, countReads };Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe JavaScript-specific trap
Performance in JavaScript, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which JavaScript type or library should I use for Decorator Pattern?
There is no decorator type; the pattern is expressed with higher-order functions for behaviour and with Proxy for transparent object wrapping. Proxy intercepts get, set, has, apply and ten other operations, and Reflect provides the default implementation of each trap so your handler can forward correctly. Standard TC39 decorators reached Stage 3 and ship in modern TypeScript and via transpilers, but are still not available unflagged in plain Node.
What is the most common JavaScript mistake when implementing Decorator Pattern?
Proxy enforces INVARIANTS and throws when you violate them: if the target has a non-configurable, non-writable property, your get trap must return exactly that value or the engine throws a TypeError at access time, so a logging proxy over a frozen object crashes in production and not in your test against a plain object. Second, private class fields (#x) are keyed to the actual instance, so calling a method through a proxy that touches #x throws TypeError: Cannot read private member. Third, a wrapper that forgets to forward this breaks every method that uses it.
How does Decorator Pattern actually perform in JavaScript?
Proxy is substantially slower than direct property access and, more importantly, it prevents V8 from using inline caches and hidden-class optimisations for the wrapped object, so the cost is not a fixed overhead but a deoptimisation of everything downstream. Keep proxies off hot paths and out of objects that are read in loops. Function wrappers are cheap by comparison, one extra call frame, and stack fine. Time complexity is O(1) and space is O(n).
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what GitHub Copilot offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.