wycats / javascript-decorators

2.4k stars 127 forks source link

property descriptor value vs initializer #57

Closed darul75 closed 8 years ago

darul75 commented 8 years ago

Hi,

When reading your specification I see that an initializer descriptor property is added and used before next defineProperty call.

But what I can not figure is why on these 2 cases initializer property is sometimes omitted.

const value = 5;

class Clazz {
  @noopDec
  prop = value

  @noopDec
  fn() {

  }
}

function noopDec(target, key, desc) {}

will give after desugaring something like

_createDecoratedClass(_temporalAssertDefined(Clazz, "Clazz", _temporalUndefined) && Clazz, [{
    key: "fn",
    decorators: [noopDec],
    value: function fn() {}
  }, {
    key: "prop",
    decorators: [noopDec],
    initializer: function initializer() {
      return 5;
    },
    enumerable: true
  }], null, _instanceInitializers);

I guess there is a reason but even after playing with babel repl I can not really figure out why.

What if I want to play with third decorator function param like this and change value at runtime, do I need to play with initializer function ? or it will never happened to play like this ? :)

function noopDec(target, key, desc) {
 if (desc.initializer) {
    const initValue = desc.initializer();
    if (initValue === 5) {
      desc.initializer = function() {
        return 4;
      }
    }
 }
 return desc;
}

I guess it is not a real case but just want to understand a little bit more :)

silkentrance commented 8 years ago

@darul75 the first case is an instance property that gets initialized in the constructor, so the initializer function generated from the assignment of value will be called in the constructor during initialization of the instance and the returned value will then be assigned to prop.

As for the decorated method fn, it does not require an initializer as it is defined on the prototype of the resulting class.

And it depends, say you want to inject a different value into prop, then you should definitely replace the initializer function, just as you did in your last example.

silkentrance commented 8 years ago

Please close as invalid/personal learning process.

darul75 commented 8 years ago

Ok thanks

silkentrance commented 8 years ago

@darul75 so if all is well, how about closing the issue then?

darul75 commented 8 years ago

Sorry pushed the wrong one