Method Decorator

홍범선·2023년 10월 31일
0

타입스크립트

목록 보기
28/34
class Idol{
  name: string;

  constructor(name: string){
    this.name = name;
  }

  @TestMethodDecorator
  @Configurable(false)
  @MethodCallLogger('PROD')
  dance(){
    return `${this.name}가 춤을 춥니다.`;
  }
}
function TestMethodDecorator(target: any, propertyKey: string, descriptor: PropertyDescriptor){
  console.log('LogCall');
  console.log('--- target ---');
  console.log(target);
  console.log('--- propertyKey ---');
  console.log(propertyKey);
  console.log('--- descriptor ---');
  console.log(descriptor);
}

const rose = new Idol('로제'); 
//TestMethodDecorator는 클래스 선언될 때 딱 한번만 실행된다.
console.log('--- run dance ---');
console.log(rose.dance()); 
// dance를 실행 했을 떄 한번 더 데코레이터가 실행이 되지 않는다. dance만 실행

Idol 클래스에 TestMethodDecorator가 데코레이터 되어 있다.
그러면 const rose = new Idol('로제')를 선언하는 순간 데코레이터함수가 실행된다.
그리고 rose.dance()를 하였을 때에는 데코레이터 함수인TestMethodDecorator은 실행하지 않고 dance함수만 실행한다.

target - static method에 데코레이팅을 할 경우 생성자 함수
- instance method에 데코레이팅 할 경우 인스턴스의 prototype
propertyKey - 메서드 이름 (여기선 dance)
descriptor - property descriptor

데코레이터 팩토리

function Configurable(Configurable: boolean){ // 이 함수를 반환하는 Factory함수를 데코레이팅
  return function(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    descriptor.configurable = Configurable;
  }
}
console.log(Object.getOwnPropertyDescriptors(Idol.prototype)); //dance의 configurable 프로퍼티가 false로 바뀜

dance 메서드의 데코레이터로 configurable 데코레이터가 있다. 하지만 데코레이터 팩토리구조이기 때문에 변수를 받을 수 있다. Configurable에 false를 전달받는다.

profile
알고리즘 정리 블로그입니다.

0개의 댓글