javascript-decorators icon indicating copy to clipboard operation
javascript-decorators copied to clipboard

De-sugaring to constructor function calls (new) instead of regular functions for decorator inheritance

Open gionkunz opened this issue 10 years ago • 3 comments

@sebmck @wycats I just messed around with this spec a bit and I actually think that inheritance of decorators would be extremely useful.

The basic idea is to switch to constructor functions instead of regular functions. I also don't see the point in building up a chain of responsibility as the descriptor object and target are modifiable within the decorator functions, so whats the point in returning the modified objects?

// Base decorator that will add the annotations to the target for run-time introspection 
class BaseClassAnnotation {
  constructor(target) {
    (target.annotations = target.annotations || []).push(this);
  }
}

// A basic annotation that extends from BaseClassAnnotation
class View extends BaseClassAnnotation {
  constructor(target, name, template) {
    super(target);
    this.name = name;
    this.template = template;
  }
}

// A decorator can still be a regular function, however, it will be treated as a constructor function
function Singleton(target, systemWide) {
  target.singleton = true;
  target.singletonSystem = !!systemWide;
}

@View('sampleView', `
  <h1>Hello World!</h1>
`)
@Singleton(true)
class Component {
  method() { }
}

Would desugar to ES6:

class Component {
  method() { }
}

new Singleton(Component, true);
new View(Component, 'sampleView', `
  <h1>Hello World!</h1>
`);

Thoughts?

Can you have a quick glance on https://github.com/gionkunz/javascript-decorators/tree/using-constructor-functions if you got time and give me some feedback?

gionkunz avatar May 02 '15 15:05 gionkunz

Why can't you inherit with regular function through composition?

RReverser avatar May 14 '15 22:05 RReverser

Well of course you can do the same with simple functional composition. I'd just prefer prototype inheritance because of various reasons where the most significant two would be 1) Tooling, as you'd have a simple static analysis to determine how decorators relate to each other / inherit from each other. 2) Complex logic in decorators can be implemented within the decorator class as functions on the same prototype, which for my taste, implies a cleaner structure.

gionkunz avatar May 25 '15 09:05 gionkunz

@gionkunz considering a class decorator, I would like to be able to replace the class by a different one that I inject in the process of the decoration.

As for inheritance, just use indirection and a framework that is capable of such indirection.

Please close, invalid.

silkentrance avatar Feb 28 '16 23:02 silkentrance