Javascript Decorators

One reason why Javascript rocks:

As a use case, imagine you want to restrict a certain set of functions to only run if you are logged in. Doing stuff like this is ridiculously easy with first-class functions.

Here’s a generic decoration example:

Update: Here’s the specific way you’d do this with node.js/Express:

Since all of the URL handlers you register have the same signature, it’s easy to add precondition checks to the handlers via decorators.

You get preconditions essentially for free, which is a damn sight better than adding the if() block to each and every handler function. Also, if you need more preconditions in the future, you can just stack them.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.