Reputation: 27791
Is it possible to implement decorators using a private method? E.g.
class Person {
@validateSomethingFirst
public doSomething() {
}
private validateSomethingFirst() { ... }
}
My initial investigation seems to indicate that this is not possible, but I can't seem to find a solid reference on this.
Upvotes: 1
Views: 918
Reputation: 22352
Yes it is possible if you declare your private method as static:
class AAA
{
private static Dec(target: any, key: string)
{
console.log("Decorator applied");
}
@AAA.Dec
public Prop: number;
}
With an instance method it will be impossible because to refer to private instance method you will need to access 'this' which will be undefined at that moment. It's easy to see why by looking at the generated JS code. If we change to instance method in the sample above - JS code will be:
var AAA = (function () {
function AAA() {
}
AAA.Dec = function (target, key) {
console.log("Decorator applied");
};
__decorate([
this.Dec,
__metadata('design:type', Number)
], AAA.prototype, "Prop", void 0);
return AAA;
})();
Here 'this' will be undefined at the moment of call.
Hope this helps.
Upvotes: 3