DEV Community

Benjamin Ajewole
Benjamin Ajewole

Posted on

Introduction to decorators in JavaScript

Image for post

Credits: Household beautiful

A decorator is a function that takes in a function as an argument and alters its behaviour without modifying the underlying function. It is written as a function closure.

Decorators vs Higher order functions

A higher-order function is a function that takes one or more functions as arguments returns a function as its result while a decorator takes is a function that takes in a function as an argument and alters its behaviour. Decorators mutate the variable while higher order functions are recommended not mutate the variable. Practically, decorators and higher order functions do the same thing.

Examples


Created a powerOf function that takes two parameters and returns the power of the two parameters.

Then, we created a logsDecorator to decorate the powerOf function by adding logs before and after the invocation of the powerOf function.

In this second example, we created a decorator to cache the results of the powerOf to avoid invoking the functions severally with the same params.

It checks if the parameters are cached, if yes, it pulls the cached result or else it invokes the function and caches the parameters and the results.

I made some changes to the third example, I made use of Class called MathsFunction with a constructor and two methods which includes powerOf and addition.

cacheDecorator takes in two parameters, the object and the function. The reason I passed the object is for it to preserve the value of this.

If you try to invoke func(), you’ll get an error that this is not defined. So, I used func.call() and passed in the object which represents this.

The call() method calls a function with a given this value and arguments provided individually.

Summary

  1. We learnt the definition of decorators.
  2. We learnt that decorators and higher order functions do the same thing.
  3. We learnt how to use decorators for logging events
  4. We learnt how to use decorator for caching
  5. We learnt that call() method calls a function with a given this value and arguments provided individually.

Top comments (0)