티스토리 뷰
반응형
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 클래스의 모든 메서드가
호출될 때마다 콘솔에 로그를 출력합니다.
반응형
'타입스크립트' 카테고리의 다른 글
타입스크립트 Property Decorator (0) | 2023.03.17 |
---|---|
타입스크립트 Method Decorator (0) | 2023.03.17 |
타입스크립트 Readonly 속성 (0) | 2023.03.17 |
Typescript 클래스와 인터페이스 (0) | 2023.03.17 |
TypeScript 함수 시그니처란? (0) | 2023.03.17 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 어려움 극복
- 자기개발
- TypeScript Guard
- Parameter Decorator
- 클래스
- 업무잘하는버
- 호이안수공예
- 타입스크립트 변수
- highcharts
- 메뉴 및 내비게이션 설계
- 사용자 중심 설계
- 공부잘하는법
- 인터페이스
- 작업팁
- 변화주기
- 당당해지기
- 경청하는자세
- typescript 사용해야하는 이유
- 라이브러리
- decorator
- 커피숖창업
- 콘텐츠 매핑
- Property Decorator
- 시안 및 프로토타입 작성
- 정보구조 설계 방법
- 피드백 수집 및 개선
- 시각적 디자인
- 호이안역사
- html
- Method Decorator
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 |
글 보관함