[TypeScript]デコレータファクトリ
/* デコレータファクトリ 言い換えると引数付デコレータ */ function logged(message = "[LOG]:"){ return function actDeco(originalMethod:any,context:any){ function loggedMethod(this:any,...args:any[]){ console.log(`${message} ${context.name} start`); const result = originalMethod.call(this,...args); console.log(`${message} ${context.name} finish`); } return loggedMethod; }; } function bound(_originalMethod:any,context:any){ context.addInitializer(function(this:any){ this[context.name] = this[context.name].bind(this); }); } class Article{ protected name:string; constructor(name:string){ this.name = name; } @bound @logged("[Article]:") showData():void{ console.log(this.name); } } const article = new Article("John Smith"); article.showData();
出力
[Article]: showData start John Smith [Article]: showData finish