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

Decorator Context Object

Exploring the context.kind, context.name, context.access, and context.addInitializer properties in detail.

Decorator Context Object

You'll learn what information the decorator context object provides and how each of its properties helps you write powerful, flexible decorators.

What Is the Context Object?

When a decorator function runs, it receives a context object as its second parameter. This object is your decorator's information hub—it tells you exactly what's being decorated and gives you tools to enhance it intelligently.

Think of the context object like a "delivery receipt" that comes with a package. It tells you what kind of package it is, where it's going, and provides a place to add special handling instructions.

The Four Key Properties

context.kind

A string indicating what is being decorated: "class", "method", "field", or "accessor". This lets you write decorators that behave differently based on target type.

context.name

The name of the decorated element (as a string or symbol). For a method called save(), context.name would be "save". This is useful for logging or metadata tracking.

context.access

An object with get and/or set methods that let your decorator read or write the decorated member at runtime. Not available for classes, but essential for field and accessor decorators that need to intercept values.

context.addInitializer

A function you can call to register a callback that runs during construction (for instance members) or class definition (for static members). Perfect for setup tasks like registering metadata or connecting to frameworks.

These properties work together: check kind to determine behavior, use name for identification, access for value manipulation, and addInitializer for lifecycle hooks.

Key Takeaway: The decorator context object provides kind, name, access, and addInitializer properties that give your decorators full awareness of what they're decorating and powerful hooks to enhance it.