How is the Decorator pattern typically implemented in JavaScript?
Short answer
By wrapping a function or object with another function that adds behavior before/after calling the original, while preserving its original interface — often done with higher-order functions rather than the class decorator proposal.
Advertisement
AModel answer
By wrapping a function or object with another function that adds behavior before/after calling the original, while preserving its original interface — often done with higher-order functions rather than the class decorator proposal.
function withLogging(fn) {
return (...args) => {
console.log('calling with', args);
return fn(...args);
};
}
const loggedAdd = withLogging((a, b) => a + b);Real-world example
Wrapping an API call function to automatically add logging or retry behavior without modifying the original function.
Likely follow-ups
- How does this differ from the experimental @decorator class syntax?
Related topics