Decorators for functions

Bob Myers rtm at
Tue Oct 20 16:24:23 UTC 2015

> You completely misunderstood me Bob.

Sorry about that.

> I was thinking about decorators for classes, when you enrich their
prototype in case the decorator receives a function instead of an object,
or you enrich the object in every other case.

Am I understanding this right that you are thinking of decorators as a type
of trait mechanism?

As I understand it, decorators are pure sugar. I like sugar as much as the
next guy, as long as it addresses common use cases, helps us write more
readable, maintainable code, and doesn't eat too much into future syntax
space. But I am on the fence about decorators.

It's worth noting that some kinds of decorators could possibly be handled
via `::` syntax:

    (function() { })::decorate_me()

However, it is worthwhile considering the Ember "computed property" use
case. For those who don't know Ember, computed properties recompute
themselves on demand when their dependencies change. This requires the
dependencies to be declared somehow. Then, the dependencies need to be
retrieved again within the function.

The classic syntax for writing computed properties is:

foo: Ember.computed('dep1', 'dep2', function() { return this.get('dep1') +
this.get('dep2'); })

An alternative in widespread use is hardly prettier, and requires polluting
the function prototype:

foo: function() { return this.get('dep1') + this.get('dep2');
}.computed('dep1', 'dep2')

The reason the Ember folks latched on to decorators is because they want to
write this:

@computed('dep1', 'dep2')
foo(dep1, dep2) { return dep1 + dep2; }

and that is indeed much better. To accomplish this, the `computed`
decorator would be roughly written as

function computed(...deps) {
  return function(target, name, descriptor) {
    var undecorated = descriptor.value;
    descriptor.value = undecorated.apply(this, =>
    return descriptor;

The above is meant merely for illustrative purposes.

The sweetness of the resulting sugar should attract a fair number of flies.


On Tue, Oct 20, 2015 at 6:30 PM, Andrea Giammarchi <
andrea.giammarchi at> wrote:
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the es-discuss mailing list