javascriptecmascript-nextangularjs-decoratorjavascript-decorators

How can I use decorators today?


I see decorators being used today already in some javascript code. My question is really two fold.

First:

If decorators have not even been finalized how is it possible to use them in production code, today? Won't browser support be non-existent?

Second:

Given it is possible to use it today, as some open source projects would suggest, what's a typically recommended setup for getting decorators to work?


Solution

  • You're right, ES2016 decorators are not yet part of the spec. But it doesn't mean we can't use it today.

    First let's take a step back and go over "what is a decorator". Decorators are simply wrappers that add behavior to an object. It's not a new concept in javascript (or programming in general), it's actually been around for a while...

    Here's a basic example of a decorator that checks permissions:

    function AuthorizationDecorator(protectedFunction) {
        return function() {
            if (user.isTrusted()) {
                protectedFunction();
            } else {
                console.log('Hey! No cheating!');
            }
        }
    }
    

    Using it would look like this:

    AuthorizationDecorator(save);
    

    You see all we're doing is simply wrapping up some other function. You can even pass a function through multiple decorators each adding a piece of functionality or running some code.

    You can even find some old articles explaining the decorator pattern in javascript.

    Now that we understand decorators are actually something we (javascript community) were always able to do, it probably comes as no shock that really when we utilize ES2016 decorators today they are simply just being compiled down to ES5 code hence why you maintain browser compatibility. So for the time being it is simply syntactic sugar (some really sweet sugar I might add).

    As for which compiler to use to convert your ES2016 code to ES5 code, you have some choices: Babel and Traceur are the most popular.

    Here's further reading on Exploring ES2016 Decorators.