Refresher: What is a decorator?
Decorators are functions which have four main capabilities when applied to a class or class element: Replacement, Initialization, Metadata, and Access
Common Use Cases
// Decorator pattern without syntax
// Option 1
class C {
// - New memoized function created
// for every instance, overhead
memoizedMethod = memoize(() => {
// ...
});
}
// Option 2
class C {
memoizedMethod() {}
static {
// - Imperative
// - Can be conditional, more complex
// - Can't be typed easily
// - Difficult to understand
C.prototype.memoizedMethod =
memoize(C.prototype.memoizedMethod);
}
}
// Decorator pattern without syntax
function memoize(fn) {
return (...args) => {
// ...impl
}
}
// + Concise, declarative, easy
// to understand
// + Performant, only one
// decorated function exists
const memoizedFunc = memoize(() => {
// ...impl
});
Number 2 most exciting feature in State of JS 2024 Survey