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:

// Decorator function
function logExecutionTime(target, key, descriptor) {
    const originalMethod = descriptor.value; // Store the original method
 
    descriptor.value = function(...args) {
        const startTime = performance.now(); // Start time
        const result = originalMethod.apply(this, args); // Call the original method
        const endTime = performance.now(); // End time
 
        console.log(`Execution time for ${key}: ${endTime - startTime} milliseconds`);
        
        return result; // Return the result of the original method
    };
 
    return descriptor; // Return the modified descriptor
}
 
// Class using the decorator
class Example {
    @logExecutionTime
    computeSquare(n) {
        return n * n;
    }
}
 
// Usage
const example = new Example();
console.log(example.computeSquare(5)); // Logs execution time and outputs: 25

Explanation:

  1. 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.
  2. Storing Original Method: Inside the decorator, we store a reference to the original method (originalMethod) so we can call it later.

  3. 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.
  4. Applying Decorator: The decorator is applied to computeSquare using the @ syntax.

  5. Using Class: When you create an instance of Example and call computeSquare, 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.