npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@darkobits/class-decorators

v4.1.11

Published

Decorator factories for classes and class methods.

Downloads

430

Readme

This package attempts to improve the way classes are decorated (see: decorator proposal) by not polluting the prototype chain, encouraging composition over inheritance.

🚧 A Note on Performance 🚧

This package makes use of Reflect.setPrototypeOf, which has known performance implications. If you need to create a million instances of a class in an environment where every millisecond counts, do not use this package. In fact, you might re-consider the usage of JavaScript at all in such cases. If, however, you are using JavaScript as a general purpose programming language to solve "normal" problems, there will be no noticable change in your application's performance characteristics. Performance benchmarks may be run via npm run perf.

Install

This package requires @babel/plugin-proposal-decorators as a peer dependency and assumes that your code is being transpiled using Babel. It also assumes you have legacy: true enabled, as it implements the legacy decorators specification.

$ npm i -D @babel/plugin-proposal-decorators
$ npm i @darkobits/class-decorators

Then, update your .babelrc file:

{
  "plugins": [
    ["@babel/plugin-proposal-decorators", {"legacy": true}]
  ]
}

Use

ClassDecorator

This package's default export is a function that accepts a decorator implementation function and returns a decorator that may be applied to a class. The decorator implementation function is passed the target class. If the decorator implementation returns a function, that function will be used as a proxy constructor for the decorated class. The proxy constructor will be passed an object with the following shape:

{
  // Array of any arguments passed to the constructor.
  args: Array<any>;
  // Invoke this function to call the decorated class' original constructor.
  constructor: Function;
  // 'this' binding, allowing the proxy constructor to be an arrow function.
  context: any;
}

Example:

In this example, we will create a higher-order decorator that accepts a list of superpowers to apply to class instances.

First, we will look at how this is done using the typical approach, then how to accomplish it using this package.

function AddSuperpowers (...powers: Array<string>): Function {
  return function (Ctor: Function): typeof Ctor {
    return class AddSuperpowers extends Ctor {
      constructor(...args: Array<any>) {
        super(...args);

        powers.forEach(power => {
          this[power] = true;
        });
      }

      hasSuperpower(power: string): boolean {
        return this[power];
      }
    }
  };
}

@AddSuperpowers('strength', 'speed', 'flight')
class Person {
  name: string;

  constructor(name) {
    this.name = name;
  }

  getName(): string {
    return this.name;
  }
}

const bob = new Person('Bob');

bob.strength; //=> true
bob.speed; //=> true
bob.flight; //=> true

This approach works, but if we examine the prototype chain of the bob instance, it will look something like this:

bob: {
  name: 'Bob'
  strength: true
  speed: true
  flight: true
  [[Prototype]] => AddSuperpowers: {
}                    hasSuperpower()
                     [[Prototype]] => Person: {
                   }                    getName()
                                        [[Prototype]] => Object
                                      }

If we used 5 decorators on the Person class, we would find 5 degrees of inheritance added to each instance of Person. Decorators should faciliate composition, not exacerbate existing issues with inheritance.

Furthermore, because we are using subclassing to implement our decorator, we are forced to call the decorated class' constructor (via super), and we must follow all of the relevant rules around when super calls must be made. This approach reduces decorators to nothing more than syntactical sugar for subclassing, and isn't really employing the Decorator Pattern.

Let's see how with a few modifications we can improve this situation:

import ClassDecorator from '@darkobits/class-decorators';

const AddSuperpowers = (...powers: Array<string>): Function => ClassDecorator(Ctor => {
  // Add a hasSuperpower method to the decorated class.
  Ctor.prototype.hasSuperpower = function (power: string): boolean {
    return this[power];
  };

  // Returning a function here will result in the function acting as a proxy
  // constructor for the decorated class.
  return function ({constructor, args}): void {
    powers.forEach(power => {
      this[power] = true;
    });

    // (Optionally) call the original constructor, forwarding any arguments
    // provided.
    constructor(...args);
  }
});


@AddSuperpowers('strength', 'speed', 'flight')
class Person {
  name: string;

  constructor(name: string) {
    this.name = name;
  }

  getName(): string {
    return this.name;
  }
}

const bob = new Person('Bob');

Notice that we now have full control over when and how the original constructor is called. We can even decide to not call it at all. And, if we looked at the protoype chain for this instance of Person, we would see:

bob: {
  name: 'Bob'
  strength: true
  speed: true
  flight: true
  [[Prototype]] => Person: {
}                    getName()
                     hasSuperpower()
                     [[Prototype]] => Object
                   }

MethodDecorator

Accepts a decorator implementation function and returns a decorator that may be applied to class methods. The decorator implementation function is passed a single object with the following shape:

{
  // Prototype object that owns the decorated method.
  prototype: object;
  // Name of the decorated method.
  methodName: string;
  // Property descriptor of the decorated method.
  descriptor: PropertyDescriptor;
}

If the decorator implementation function returns a function, the returned function will act as a proxy for the original method. The proxy will be invoked each time the original method is called, and is passed a single object with the following shape:

{
  // Any arguments passed to the method call.
  args: Array<any>;
  // Original method, pre-bound to the class instance.
  method: Function;
}

Example:

import {MethodDecorator} from '@darkobits/class-decorators';

const AddSalutation = MethodDecorator(({prototype, methodName}) => {
  // Optionally manipulate prototype here.

  // Return a function which will serve as a delegate for the original method.
  return ({args, method}) => `Hello, my name is ${method()}.`;
});

class Person {
  name: string;

  constructor(name: string): void {
    this.name = name;
  }

  @AddSalutation
  getName(): string {
    return this.name;
  }
}

const bob = new Person('Bob');
bob.getName() //=> 'Hello, my name is Bob.'