Sobes.tech
Junior — Middle

Can decorators be used only for class methods or also for other elements?

sobes.tech AI

Answer from AI

Decorators in JavaScript (and Node.js) can be applied not only to class methods but also to other elements, depending on support and the syntax used. In the ECMAScript standard, decorators are initially intended for classes and their methods, but in some implementations and with transpilers (e.g., Babel), decorators can be applied to class properties, method parameters, and even to classes themselves.

Example of using a decorator for a class method:

function log(target, key, descriptor) {
  const original = descriptor.value;
  descriptor.value = function(...args) {
    console.log(`Calling ${key} with arguments:`, args);
    return original.apply(this, args);
  };
  return descriptor;
}

class Example {
  @log
  say(message) {
    console.log(message);
  }
}

const e = new Example();
e.say('Hello');

Thus, decorators are applicable not only to methods but also to other class elements if the runtime environment or bundler supports it.