JavaScript Decorators

Okay, so JavaScript decorators do make my brain melt a bit. I’ve been reviewing them, and have realized I just have to memorize some syntax in order to remember how to do them regularly.

As a way to help myself remember how to make/use them in the future, I thought I’d just jot down a couple rules that I think I’ve caught onto. Hopefully these will help future me or any other poor soul who has to wrestle with this somewhat confusing design pattern. Here are the 2 rules I’ve picked up on:

  1. The decorator function has to store things within its own scope that are going to be accessed within the function it is returning.
  2. Any code that change’s the value of variables inside the decorator’s scope should be changed INSIDE the function the decorator is returning.
  3. (bear with me, this one will sound odd) The function that is being “decorated” must be called inside the function that is being returned by the decorator. Don’t return the function itself. (In fact, I don’t think you want to return anything at all in the inner function — just call the function)

So from my perspective, it seems the basic formula for a decorator function is as follows:

function decoratorFunction(normalFunction) {
// the initial condition
var someCondition = false;
return function() {
// check if the condition has been met yet
if (!someCondition) {
normalFunction();
// then whatever makes your condition change happens
someCondition = true;

Anyway, that’s what I’ve learned about decorators so far. If anyone has any additional examples/ideas/questions/corrections, please don’t hesitate to comment or send me a message! This is a tricky topic, and I’d be happy to be further educated about it.


Originally published at paloobi.tumblr.com.

Show your support

Clapping shows how much you appreciated Alexandra Polubiec’s story.