TypeScript Guidebook
  • TypeScript 가이드북
  • 소개
    • TypeScript를 사용하는 이유
  • 환경 구성 / CLI
    • 컴파일 설정
    • 린팅
    • IDE / 에디터
    • Google TypeScript Style
    • TSDX
  • 타입
    • primitive 타입
    • any 타입
    • array 타입
    • tuple 타입
    • enum 타입
    • function / union / void 타입
    • object 타입
    • null / undefined 타입
    • never 타입
    • 사용자 정의 타입
    • 타입 어설션
  • TS vs ES6
    • 블록 영역 변수, 상수 선언
    • 템플릿 리터럴
    • 화살표 함수
    • 전개 연산자 / 매개변수
    • 비구조화 할당
  • 클래스
    • 속성 with 접근 제어자
    • 메서드 with 접근 제어자
    • 상속
    • 게터 / 세터
    • 스태틱 속성, 메서드
    • 추상 클래스
    • 싱글턴
    • 읽기전용 속성
  • 네임스페이스와 모듈
    • 네임스페이스
    • 네임스페이스 멀티 파일
    • 네임스페이스 중첩
    • 모듈
    • 모듈 번들링
  • 인터페이스
    • 인터페이스와 클래스
    • 인터페이스와 매개변수
    • 인터페이스와 객체 리터럴
    • 인터페이스 옵션 속성
    • 인터페이스 읽기 전용 속성
    • 인덱스 시그니처 속성
    • 인터페이스와 함수타입
    • 인터페이스 확장
  • 제네릭
    • 제네릭과 클래스
    • 제네릭과 함수
    • 멀티 타입 설정
    • 타입 변수 상속
  • 데코레이터
    • 데코레이터 / 팩토리
    • 데코레이터 구성
    • 클래스 데코레이터
    • 메서드 데코레이터
    • 접근 제어자 데코레이터
    • 속성 데코레이터
    • 매개변수 데코레이터
Powered by GitBook
On this page
  • getters / setters
  • 실습
  • 참고
  1. 클래스

게터 / 세터

getters / setters

비공개로 설정할 필요가 있는 속성을 private로 설정한 후, 이 속성에 접근하여 값을 읽거나, 쓰기 위한 Getter, Setter 함수를 사용하여 속성을 정의할 수 있습니다.

class Plant {

  // 비공개 속성 '종(Species)'
  private _species:string|null = null;

  // getter 함수
  get species(): string {
    return this._species;
  }

  // setter 함수
  set species(value:string) {
    if ( value.length > 3 ) { this._species = value; }
  }

}


/* 인스턴스 생성 ------------------------------------------------ */

let plant = new Plant();

console.log(plant.species); // null

plant.species = '줄기';

console.log(plant.species); // null

plant.species = '푸른 식물';

console.log(plant.species); // '푸른 식물'

JavaScript(ES5)로 컴파일된 코드를 살펴보면 Object.defineProperty()를 사용하여 get, set 함수를 사용하여 동일하게 작동하도록 처리한 것을 확인할 수 있습니다.

컴파일 코드:

JavaScript
var Plant = /** @class */ (function () {
  function Plant() {
    this._species = 'Default';
  }
  Object.defineProperty(Plant.prototype, "species", {
    // getter
    get: function () {
      return this._species;
    },
    // setter
    set: function (value) {
      if (value.length > 3) {
        this._species = value;
      }
    },
    enumerable: true,
    configurable: true
  });
  return Plant;
}());


/* 인스턴스 생성 ------------------------------------------------ */

var plant = new Plant();

console.log(plant.species); // null

plant.species = '줄기';

console.log(plant.species); // null

plant.species = '푸른 식물';

console.log(plant.species); // '푸른 식물'

실습

참고

Previous상속Next스태틱 속성, 메서드

Last updated 6 years ago

Handbook - Classestypescriptlang
TypeScript - getters / setters
Logo