デコレーター
関数や、変数にアクセスするとき、前処理を挿入できる。
compileすると、.jsファイルができる。
tsc –target ES5 –experimentalDecorators deco.ts
deco.ts
//1. デコレーターファクトリー
function deco() {
console.log("deco(): evaluated");
return function (target, propertyKey: string, descriptor: PropertyDescriptor) {
console.log("deco(): called");
}
}
class A{
@deco()
greeter(person:string) {
return "Hello, " + person;
}
}
// メソッドデコレーター
function method_deco(target, propertyKey: string, descriptor: PropertyDescriptor) {
console.log("method_deco(): called");
}
// クラスデコレーター
function class_deco(fnc: Function){
console.log("class_deco(): called");
}
// パラメーターデコレーター
function param_deco(target: any, props: string, index: number) {
console.log("param_deco(): called");
}
@class_deco
class B{
@method_deco
hoge(@param_deco person:string) {
return "Hello, " + person;
}
}
let user = "yamada taro";
let a = new A();
let b =new B();
document.body.innerHTML = a.greeter(user);
document.body.innerHTML += b.hoge(user);
test.html
<!DOCTYPE html>
<html>
<head><title>TypeScript Greeter</title></head>
<body>
<!-- <script src="greeter.js"></script> -->
<!-- <script src="class.js"></script> -->
<script src="deco.js"></script>
</body>
</html>
デコレーターの呼ばれる順番
deco(): evaluated
deco(): called
param_deco(): called
method_deco(): called
class_deco(): called

