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

Accessor Decorators (Getters and Setters)

Understand how decorators modify or wrap getter/setter pairs to add validation or side effects.

Accessor Decorators (Getters and Setters)

You'll learn how decorators can wrap or modify getter/setter pairs to add validation, logging, or other side effects.

What Are Accessor Decorators?

Accessor decorators target getter and setter pairs in a class. When you apply a decorator to an accessor (a property defined with get or set), you can intercept access to that property and inject custom behavior—like validating values before setting them, logging access patterns, or triggering side effects.

How They Work

An accessor decorator receives a context object that includes information about the accessor being decorated. You can return a replacement accessor object with new get and/or set functions that wrap the original behavior.

Think of it like installing a security checkpoint at a property's entrance: every read or write must pass through your custom logic first.

Typical Use Cases

Validation: Ensure a setter only accepts valid values before storing them.

Logging: Track when properties are read or modified for debugging.

Side effects: Trigger updates or notifications when a property changes (useful for reactive patterns).

Computed caching: Optimize expensive getter calculations by caching results.

The Decorator Pattern

When decorating an accessor, you typically:

  1. Receive the original accessor definition
  2. Create wrapper get and set functions
  3. Call the original functions inside your wrappers
  4. Add your custom logic before or after the original behavior
  5. Return the new accessor object

Key Takeaway: Accessor decorators wrap getter/setter pairs to inject validation, logging, or side effects while preserving the original property access behavior—perfect for enforcing rules or observing changes transparently.