[TypeScript] 타입스크립트 Getter & Setter / readonly / static
글 작성자: 망고좋아
반응형
🎯 타입스크립트 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.
를 붙인다.
📌 참고
반응형
'프로그래밍 > TypeScript' 카테고리의 다른 글
[TypeScript] 타입스크립트 제네릭(Generic), Factory Pattern with Generics (0) | 2021.11.27 |
---|---|
[TypeScript] 타입스크립트 인터페이스(Interface), Strategy pattern (0) | 2021.11.27 |
[TypeScript] 타입스크립트 Class 접근 제어자 (0) | 2021.11.24 |
[TypeScript] 타입스크립트 클래스 사용하기 - 상속, 추상 클래스, 추상 클래스를 활용한 디자인 패턴(Template Method Pattern) (0) | 2021.11.24 |
[TypeScript] 타입스크립트 함수 사용하기 (0) | 2021.11.24 |
댓글
이 글 공유하기
다른 글
-
[TypeScript] 타입스크립트 제네릭(Generic), Factory Pattern with Generics
[TypeScript] 타입스크립트 제네릭(Generic), Factory Pattern with Generics
2021.11.27 -
[TypeScript] 타입스크립트 인터페이스(Interface), Strategy pattern
[TypeScript] 타입스크립트 인터페이스(Interface), Strategy pattern
2021.11.27 -
[TypeScript] 타입스크립트 Class 접근 제어자
[TypeScript] 타입스크립트 Class 접근 제어자
2021.11.24 -
[TypeScript] 타입스크립트 클래스 사용하기 - 상속, 추상 클래스, 추상 클래스를 활용한 디자인 패턴(Template Method Pattern)
[TypeScript] 타입스크립트 클래스 사용하기 - 상속, 추상 클래스, 추상 클래스를 활용한 디자인 패턴(Template Method Pattern)
2021.11.24