Course contentsShow
← JavaScript
Lesson 2074 of 2,72343. DecoratorsFree lesson

Accessor Decorators

Decorating getter and setter methods to intercept property access and control read/write behavior.

Accessor Decorators

You'll learn how to intercept and control property access by decorating getter and setter methods.

The Core Idea

Accessor decorators let you wrap get and set methods with custom logic, giving you fine-grained control over how properties are read and written. While field decorators work on class fields and method decorators work on functions, accessor decorators specifically target the getter/setter pair that controls property access.

Think of accessor decorators like installing a security checkpoint at a building's entrance and exit. Everyone accessing the property must pass through your checkpoint, where you can log visits, validate credentials, or transform what they see.

How Accessor Decorators Work

When you decorate a getter or setter, the decorator function receives a context object describing the accessor. You can return a new getter/setter pair that wraps the original behavior:

function logged(value, context) {
  if (context.kind === "accessor") {
    return {
      get() {
        console.log(`Getting ${context.name}`);
        return value.get.call(this);
      },
      set(newValue) {
        console.log(`Setting ${context.name} to ${newValue}`);
        value.set.call(this, newValue);
      }
    };
  }
}

class Box {
  @logged
  accessor contents = "empty";
}

const box = new Box();
console.log(box.contents); // Logs: "Getting contents", then "empty"
box.contents = "full";     // Logs: "Setting contents to full"

The decorator intercepts every read and write operation, letting you add validation, logging, transformation, or access control without polluting the class's main logic.

Key Takeaway: Accessor decorators wrap getter/setter methods to intercept property access, enabling you to control, validate, or monitor every read and write operation transparently.