Decorators on functions

JavascriptBabeljsDecoratorEcmascript NextJavascript Decorators

Javascript Problem Overview


I see that babel.js decorators (available in "stage 1") implement the spec at https://github.com/wycats/javascript-decorators. It appears that decorators are limited to (1) classes, (2) accessors, and (3) methods. In my case, I want to use decorators on plain old functions, as in

@chainable
function foo() { }

where (just an example)

function chainable(fn) {
  return function() {
    fn.apply(this, arguments);
    return this;
  };
}

I don't see any logical reason why decorators should not be able to apply to functions. My question is, is there some way to accomplish this? Or is there some good reason why functions cannot be decorated?

It turns out there is an issue raised for this at https://github.com/wycats/javascript-decorators/issues/4.

Javascript Solutions


Solution 1 - Javascript

To execute a decorator, you evaluate an expression and doing that prevents hoisting (even for a variable declaration, the right-hand side of an assignment stays put). Therefore, it is not compatible with function declarations being hoisted.

As a work-around, I suggested that function expressions, generator function expressions and arrow functions could be enabled to be decorated:

const func = @someDecorator('abc') (x, y) => { return x + y };

Alas, that wasn’t met with much enthusiasm: Decorators for functions

Solution 2 - Javascript

You certainly have a point here.

But as neo_blackcap pointed out, function decorator are not part of the ES7 decorators draft.

So, the best thing you can do is to start discussion on the corresponding tracker to attract community attention to your proposal.

ES7 decorators are on their first stage of development second stage of development, meaning that their API is still under development and could undergo any change.

Solution 3 - Javascript

I think the problem is function decorator has not been ES7 draft.

Of course, you still can implement your function decorator by yourself

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser663031View Question on Stackoverflow
Solution 1 - JavascriptAxel RauschmayerView Answer on Stackoverflow
Solution 2 - JavascriptLeonid BeschastnyView Answer on Stackoverflow
Solution 3 - JavascriptNeo KoView Answer on Stackoverflow