패스트캠퍼스 TypeScript 강의 Ch 6. Class 복습 내용
참고링크
클래스는 객체를 생성하는 템플릿의 기능을 한다. property와 method를 포함하는 형태이며, 객체 생성시 property를 초기화하는 constructor() 메서드가 포함된다.
// 기본 형식
class Dog {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
hello() {
console.log(`제 강아지 ${this.name}는 ${this.age}살 입니다.`);
}
}
const myPuppy = new Dog('Komma', 4);
myPuppy.hello(); // 제 강아지 Komma는 4살 입니다.
java에서 사용하는 public, private, protected 와 동일한 형태로 사용 가능하며, 접근제어자 생략시 기본 값은 public으로 지정된다. (java의 경우 protected)
클래스의 프로퍼티에 접근하며, 값을 얻거나 수정할 때 사용하는 메서드이다.
class Dog{
constructor(_name: string, age: number) {}
// method와 구분짓기 위해 property 앞에 _사용
get name() { // Getter
return this._name;
}
set name(n: string) { // Setter
this._name = n;
}
}
읽기 전용 속성으로 클래스의 프로퍼티 값을 초기화한 뒤에는 재할당 할 수 없다.
(초기화는 클래스의 프로퍼티 선언부와 constructor() 함수 내에서만 가능)
class Person {
readonly name: string = 'Haryun';
private readonly country: string;
constructor(public _name: string) {
this.country = 'Korea';
}
hello() {
this.country = 'America'; // error
}
}
클래스의 프로퍼티를 동적으로 지정할 때 사용한다.
class Students { // < 학생의 이름: 성별 > 형식
[index: string]: 'male' | 'female';
// [index: string]: string; 도 가능하지만 성별과 무관한 값을 넣을 수 있기때문에 명확하게 표현하는 것이 좋음
}
const a = new Students();
a.Haryun = 'female';
a.Harin = 'female';
a.Hakseong = 'male';
console.log(a); // Students {Haryun: 'female', Harin: 'female', Hakseong: 'male'}
클래스의 프로퍼티나 메서드에 static 키워드를 사용하면 인스턴스를 생성하지 않아도 사용할 수 있으며, 해당 클래스를 사용하는 객체끼리 값을 공유한다.
class StaticTest {
static country = 'Korea';
static sayHello() {
console.log(`안녕하세요. 이곳은 ${this.country} 입니다.`);
}
}
StaticTest.sayHello(); // 안녕하세요. 이곳은 Korea 입니다.
StaticTest.country = 'America';