재학습/NestJS

[NestJS] [데코레이터] 접근자 데코레이터

재삉 2023. 6. 20. 18:00
반응형

접근자 데코레이터

접근자 바로 앞에 선언

접근자의 속성 설명자에 적용

접근자의 정의를 읽거나 수정할 수 있음

선언파일과 선언클래스에는 사용할 수 없음

반환값은 해당 멤버의 속성 설명자

 

 

구현

특정 멤버가 열거가 가능한지 결정하는 데코레이터

export class AccessorDecorationTest {
  constructor(private name: string) {}

  @Enumerable(true)
  get getName() {
    return this.getName;
  }

  @Enumerable(false)
  set setName(name: string) {
    this.name = name;
  }
}

function Enumerable(enumerable: boolean) {
  return function (
    target: any,
    propertyKey: string,
    descriptor: PropertyDescriptor
  ) {
    descriptor.enumerable = enumerable;
  };
}
accessorDeco(): string {
    const testInstance = new AccessorDecorationTest('jayden');
    for (const key in testInstance) {
      console.log(key);
    }
    return 'accessor decorator test';
  }

 

실행결과

conosle.log(key)를 실행해보면 name과 getName만 나오게된다.

왜냐하면 setName은 열거가능여부를 false로 두었기 때문이다.

 

setName의 Enumerable을 true로 변경한다면?

setName까지 출력이 가능하다.

반응형