Skip to content

JavaScript - Decorators ​

Decorators Proposal ​

  • Proposal defined in tc39/proposal-decorators
  • Orthogonal Classesand Class Evaluation Order Based on the proposal, Decorators and Class Field and Private methods propose a combined vision of how to make them work together
  • Decorators are useful for adding functionality without modifying the code of already defined classes, functions, and variables.
  • It is used for memoization, access control, authentication, instrumentation, timing processing, logging, rate limiting, etc.

Decorators Practicality ​

Decorators are not available in JavaScript, but Decorators in TypeScript You can use it. That's why Node.js Framework nestjs and Front-end Framework Angular is officially in use.

Code Usage Examples ​

  • @defineElement: Ability to create custom elements
  • @bound: Debounce processing function
  • @observed: A function that monitors the field and automatically calls when it changes.
js
@defineElement('num-counter')
class Counter extends HTMLElement {
  @observed #x = 0;

  @bound
  #clicked() {
    this.#x++;
  }

  constructor() {
    super();
    this.onclick = this.#clicked;
  }

  connectedCallback() {
    this.render();
  }

  @bound
  render() {
    this.textContent = this.#x.toString();
  }
}