글 작성자: 망고좋아
반응형

🎯 타입스크립트 Getter & Setter / readonly / static

📝 타입스크립트 Getter & Setter

const fullNameMaxLength = 10;

class Employee {
  private _fullName: string;

  get fullName(): string {
    return this._fullName;
  }

  set fullName(newName: string) {
    if (newName && newName.length > fullNameMaxLength) {
      throw new Error("fullName has a max length of " + fullNameMaxLength);
    }

    this._fullName = newName;
  }
}

let employee = new Employee();

employee.fullName = "Bob Smith";

if (employee.fullName) {
  console.log(employee.fullName);
}
  • 비공개로 설정하려는 속성은 private로 설정하고, 속성 값을 읽고 수정하는 getter/setter 함수를 사용한다.
  • class의 속성에 직접 접근하는 것을 막고, getter / setter 함수를 사용해 값을 받아오거나 수정한다.
  • 속성에 직접 접근해 수정하면 데이터 무결성이 깨질 수 있다. (캡슐화 권장)
  • 각 객체의 멤버에 접근하는 방법을 세밀하게 제어할 수 있다.

 

📝 readonly

class Octopus {
  readonly name: string;
  readonly numberOfLegs: number = 8;
  constructor(theName: string) {
    this.name = theName;
  }
}
let dad = new Octopus("Man with the 8 strong legs");
dad.name = "Man with the 3-piece suit"; // 오류! name은 읽기전용 입니다.
  • 속성을 읽기 전용으로 설정해 변경할 수 없게 만든다.
  • 선언될 때나 생성자에서 값을 설정하면 이후 수정할 수 없다.
  • readonly키워드를 사용하여 프로퍼티를 읽기 전용으로 만들 수 있다. 읽기 전용 프로퍼티들은 선언 또는 생성자에서 초기화해야 합니다.

 

📝 static

class Grid {
  static origin = { x: 0, y: 0 };
  calculateDistanceFromOrigin(point: { x: number; y: number }) {
    let xDist = point.x - Grid.origin.x;
    let yDist = point.y - Grid.origin.y;
    return Math.sqrt(xDist * xDist + yDist * yDist) / this.scale;
  }
  constructor(public scale: number) {}
}

let grid1 = new Grid(1.0); // 1x scale
let grid2 = new Grid(5.0); // 5x scale

console.log(grid1.calculateDistanceFromOrigin({ x: 10, y: 10 }));
console.log(grid2.calculateDistanceFromOrigin({ x: 10, y: 10 }));
  • 전역 멤버를 선언할 때 사용
    • 전역 멤버 : 객체마다 할당되지 않고 클래스의 모든 객체가 공유하는 멤버
  • 각 인스턴스가 아닌 클래스 자체에서 보이는 전역 멤버를 생성한다.
  • 범용적으로 사용되는 값에 설정한다.
  • 클래스명.을 앞에 붙여 static 멤버에 접근할 수 있다.
  • ES6에서는 메서드 전용 속성에는 선언이 안 되었으나, TS에서는 사용할 수 있다.
  • 이 예제에서는 모든 grid의 일반적인 값이기 때문에 origin에 static을 사용한다.
  • 각 인스턴스는 클래스 이름을 앞에 붙여 이 값에 접근할 수 있다. 인스턴스 접근 앞에 this.를 붙이는 것과 비슷하게 여기선 전역 접근 앞에 Grid.를 붙인다.

 

📌 참고

반응형