https://github.com/tc39/proposal-decorators#class-fields
[[クラス (JavaScript)|クラス]]の[[フィールド (JavaScript)|フィールド]]に対して設定する[[デコレーター (JavaScript)|デコレーター]]。
デコレーター設定時には`value`に値が入らないが、`this`と値を引数にとり加工後の値を返却する関数をreturnすることで、値を制御する。
サンプルコードは[[TypeScript]]の[[デコレーター (TypeScript)|デコレーター]]。
```ts
function transform(args?: { upper?: boolean; lower?: boolean }) {
console.log("Execute transform");
return function (value: undefined, context: ClassFieldDecoratorContext) {
console.log("Execute a fuction in transform");
return function (this: unknown, v: string) {
console.log("Execute a function in another fuction in transform");
if (args?.upper) {
return v.toUpperCase();
}
if (args?.lower) {
return v.toLowerCase();
}
return v;
};
};
}
class Color {
@transform({ upper: true })
first: string = "First";
@transform({ lower: true })
last: string = "Last";
@transform()
end: string = "End";
}
console.log("Before initialize Color");
const c = new Color();
console.log("After initialize Color");
console.log(c);
```
```console
Execute transform
Execute transform
Execute transform
Execute a fuction in transform
Execute a fuction in transform
Execute a fuction in transform
Before initialize Color
Execute a function in another fuction in transform
Execute a function in another fuction in transform
Execute a function in another fuction in transform
After initialize Color
Color { first: 'FIRST', last: 'last', end: 'End' }
```
> [!attention]
> [[クラスフィールドデコレーター (JavaScript)|クラスフィールドデコレーター]]が動作するのは **[[フィールド (TypeScript)|フィールド]]の初期化時** のみ。**[[フィールド (JavaScript)|フィールド]]への代入時には動作しない** ので注意。具体的には
> ```ts
> const c = new Color();
> c.first = "Hoge";
> ```
> のように代入して、`console.log(c.first)`としても結果は`HOGE`にならない。`Hoge`のまま。