Search code examples
javascriptdecoratorecmascript-harmonyecmascript-2016

Does the ES7 decorator spec require descriptors to have an `initializer` method


Using Babel to transpile the following es7 code:

let obj = {
  @decorate
  prop: 10
}

let decorate = ( object, propertyName, desc ) => desc

When decorate is called, the property descriptor desc contains a method named initializer, that returns the value of obj.prop when executed.

Is the initializer method part of the es7 Decorator specification, or is this purely a side effect of Babel converting to es5?


Solution

  • es7 Decorator specification

    Notice there is neither ES7 yet nor a specification for decorators. There's a draft, a harmony proposal, for how the language may be extended.

    When decorate is called, the property descriptor desc contains a method named initializer

    That's a bit odd. From the current proposal I would have expected that the decorator is always called with the property descriptor for that property, which would be

    {value: 10, writable: true, enumerable: true, configurable: true}
    

    for your example. However, the examples in the draft do only outline decorators for methods (and accessor properties), both on classes and object literals, but not for value properties.

    Is the initializer method part of the Decorator proposal?

    Not currently, but there is a INITIALIZER_INTEROP.md file in their repository which outlines interoperability of decorators with the PropertyInitialisers from the class properties proposal (which is an unfinished draft, but already implemented in babel, as well). It does indeed use static decorators which are given descriptors with an initializer function that would be evaluated to initialise the instance property in (before) the constructor.

    is this purely a side effect of Babel converting to es5?

    Not really. IMO it's just a bug, probably stemming from how babel transpiles class properties, which makes them look the same as value properties on an object literal.