티스토리 뷰

반응형

TypeScript Class Decorator는 클래스 선언을 수정하는 함수입니다. 클래스 또는 클래스 멤버에 메타데이터를 추가하거나 클래스를 수정하는데 사용됩니다. 이는 클래스의 동작을 변경하거나 클래스의 인스턴스를 생성하기 전에 클래스를 수정할 필요가 있을 때 유용합니다.

어떻게 사용하나요?

Class Decorator는 클래스 선언 바로 앞에 위치하며, 다음과 같이 @ 키워드 뒤에 데코레이터 함수를 작성하여 사용할 수 있습니다.

@decorator
class MyClass {}

예제

다음 예제는 클래스를 수정하는 Class Decorator를 보여줍니다. 이 예제에서는 클래스의 모든 메서드가 실행될 때마다 콘솔에 로그를 출력합니다.

function logMethods(target: any) {
  // target.prototype에는 클래스의 프로토타입이 들어있습니다.
  const methods = Object.getOwnPropertyNames(target.prototype);

  for (let i = 0; i < methods.length; i++) {
    const methodName = methods[i];
    const originalMethod = target.prototype[methodName];

    // 새로운 함수를 만듭니다.
    const newMethod = function(...args: any[]) {
      console.log(`Method ${methodName} called with arguments: ${args}`);

      // 원래의 메서드를 실행합니다.
      return originalMethod.apply(this, args);
    };

    // 새로 만든 함수로 원래의 메서드를 덮어씁니다.
    target.prototype[methodName] = newMethod;
  }
}

@logMethods
class MyClass {
  method1(arg1: string, arg2: number) {
    console.log('Method 1 called');
  }

  method2() {
    console.log('Method 2 called');
  }
}

const instance = new MyClass();
instance.method1('hello', 3);
instance.method2();

위 코드를 실행하면 다음과 같은 결과가 나타납니다.

Method method1 called with arguments: hello,3
Method 1 called
Method method2 called with arguments:
Method 2 called

위 코드에서는 @logMethods 데코레이터 함수를 사용하여 MyClass 클래스의 모든 메서드가

호출될 때마다 콘솔에 로그를 출력합니다. 

 

반응형
댓글