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

Class Decorators

Applying decorators to entire class declarations to modify or replace the class constructor.

Class Decorators

You'll learn how to apply decorators to entire class declarations to modify or replace the class constructor.

What Class Decorators Do

A class decorator is a function that wraps around a class declaration, giving you the power to modify, replace, or extend the entire class before it's used. Think of it like a factory wrapper around your class—it receives the class definition and can return either the original class, a modified version, or an entirely new class that takes its place.

How Class Decorators Work

When you place a decorator above a class declaration using @decoratorName, JavaScript calls that decorator function once when the class is defined, passing it a single argument: the class itself (the constructor function). The decorator can then:

  • Return the original class unchanged
  • Return a modified version of the class
  • Return a completely new class to replace it

The decorator's return value becomes the actual class that code will use.

Decorator Function Structure

function myClassDecorator(targetClass, context) {
  // targetClass: the class constructor
  // context: metadata about where this decorator is applied
  
  // You can modify targetClass here
  // Or return a new class entirely
  return targetClass; // or return a replacement
}

The context object includes properties like kind (which will be "class"), name (the class name), and other metadata useful for advanced scenarios.

Common Use Cases

Class decorators excel at cross-cutting concerns: adding logging, registering classes in a registry, enforcing interfaces, or wrapping all methods with error handling.

Key Takeaway: Class decorators intercept class declarations, receiving the constructor and context, then return the class to use—enabling powerful metaprogramming patterns for modifying entire classes at definition time.