Decorator
A decorator wraps an object or function and adds behaviour while keeping the same calling shape. The caller still calls save(user); logging, retry, or access control happen in the wrapper.
Detailed Explanation
The word collides with two JS features. Decorator pattern is a wrapper object. Decorators (@logged) are a language proposal / TypeScript feature that apply wrappers at definition time. The pattern does not need @.
A function decorator:
function withLog(fn) {
return function wrapped(...args) {
console.log("call", fn.name);
return fn.apply(this, args);
};
}
An object decorator implements the same methods and forwards, plus extra work: a CachedStore around a Store, a GzipResponse around a Response. In class form this is composition, not extends (though extends can look similar).
JavaScript makes function decorators cheap because functions are values. redux middleware, Express wrappers, and once(fn) are decorators. Higher-order components in React are the same idea for UI.
Keep the contract. If save returns a promise, the wrapper should return a promise. If save uses this, the wrapper must apply. If you add methods the inner object does not have, callers depend on the wrapper and cannot unwrap easily.
What it costs you: stack depth and identity. wrapped !== fn, so removeEventListener and Set membership break if you decorate after subscribe. Decorators that allocate per call (new closures in a hot path) show up in profiles. Nested wrappers make stack traces longer.
Reach for a decorator when many functions need the same extra policy (timing, auth). Reach for middleware when the wrap is a pipeline of request/response. Reach for a subclass when you are specialising a type, not wrapping an instance you were given.
Decorators compose. withLog(withRetry(fn)) and withRetry(withLog(fn)) are different: the first logs one call and retries silently; the second logs every attempt. Write the order down. In TypeScript, keep the wrapped function's type with a generic so the caller still sees the original signature, not Function.
A decorator that swallows errors to "be resilient" hides outages. Retry only the errors you named (network, 503), then throw.
Code Examples
function withRetry(fn, times = 2) {
return async function wrapped(...args) {
let last;
for (let i = 0; i < times; i += 1) {
try {
return await fn(...args);
} catch (err) {
last = err;
}
}
throw last;
};
}
let n = 0;
const flaky = async () => {
n += 1;
if (n < 2) throw new Error("fail");
return "ok";
};
const stable = withRetry(flaky, 3);
stable().then(console.log); // => okfunction cached(fn) {
const memo = new Map();
return function wrapped(key) {
if (memo.has(key)) return memo.get(key);
const value = fn(key);
memo.set(key, value);
return value;
};
}
const twice = cached((x) => x * 2);
console.log(twice(4), twice(4)); // => 8 8Common Gotchas
The wrapper is a different function
bind and unsubscribe with the wrapper reference, not the inner `fn`.
Losing `this`
use `fn.apply(this, args)` when decorating methods.
`@decorator` syntax is not required
a higher-order function is the pattern.
Caches in decorators are process-wide if the wrapper is a singleton
evict or key by request.