Cristi Salcescu detailed post on Decorators. Method decorators are a tool for reusing common logic. They are complementary to Object Oriented Programming. Decorators encapsulate responsibility shared by different objects.
A function decorator is a higher-order function that takes one function as an argument and returns another function, and the returned function is a variation of the argument function.
The blog post then walks through some common use cases for Decorators:
- Log duration
- Authorization
- compose() – apply multiple decorators the new composed decorator to the original function
- Order, when execution order of decorators matter
Author then explains what are Factory Functions and how to decorate the Factory Function. He favors factory functions over classes for the flowing reasons:
- Encapsulation. Members are private by default.
- There are no issues with this losing context.
- Objects have a better security. The internal state is encapsulated and the API is immutable.
Further resources to extend your knowledge with links to external resources are also provided. Good read for any JavaScript fun!
[Read More]