2022-06
Decorators can add initializers with the `addInitializer` method of the context object. These added-initializers run in 1 of 3 phases, depending on the value being decorated.
@dec
class C {
foo = 123;
@dec bar() {}
static foo = 123;
@dec static bar() {}
}
// Approximate transpilation
class C {
foo = (runInstanceInitializers(this), 123);
bar() {}
static foo = (runStaticInitializers(this), 123);
static bar() {}
}
runClassInitializers(C);
First parameter to `addInitializer` determines placement. Can be "instance", "static", or "class". Benefits:
function dec(value, context) {
context.addInitializer('instance', () => {
console.log('instance!')
});
context.addInitializer('static', () => {
console.log('static!')
});
context.addInitializer('class', () => {
console.log('class!')
});
}
@dec class C {}
// static! class!
new C();
// instance!