Artigo interessante sobre as decorators em Javascript: https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841
Example
By ChatGPT:
In JavaScript, a decorator is a function that takes another function or method and extends its behavior without modifying its structure. Decorators are commonly used in frameworks like Angular and can be implemented in plain JavaScript as well.
Here’s a simple example of a decorator that logs the execution time of a function:
Explanation:
-
Decorator Function:
logExecutionTime
is defined as a decorator. It takes three parameters:target
: The prototype of the class or constructor function.key
: The name of the method being decorated.descriptor
: The property descriptor for the method.
-
Storing Original Method: Inside the decorator, we store a reference to the original method (
originalMethod
) so we can call it later. -
Modifying Behavior: We override
descriptor.value
with a new function that:- Records the start time.
- Calls the original method using
apply
. - Records the end time and logs out how long it took to execute.
-
Applying Decorator: The decorator is applied to
computeSquare
using the@
syntax. -
Using Class: When you create an instance of
Example
and callcomputeSquare
, it will log how long that computation took to complete.
This is just one simple way to use decorators in JavaScript! You can create various decorators based on your needs by modifying how they wrap around methods or functions.