객체(클래스)에서는 행동을 뜻한다.
introduce(): string {
return `${this.name}의 나이는 ${this.age} 입니다.`
};
비공개로 설정할 필요가 있는 속성을 private로 설정한 후, 이 속성에 접근하여 값을 읽거나, 쓰기 위한 Getter, Setter 함수를 사용하여 속성을 정의할 수 있습니다.
// 클래스
class Person {
// 필드
name: string;
private _age: number;
readonly location: string = "Korea";
// 생성자
constructor(name: string, age: number) {
this.name = name;
this._age = age;
};
// get
get age() {
if (this._age === 0) {
return '나이를 설정하십시오.';
};
return `나이는 ${this._age}세 입니다.`;
};
// set
set age(age) {
if (typeof age === 'number') {
this._age = age
};
this._age = 0;
}
};
// 인스턴스
const student1 = new Person('Jeong', 56);
const student2 = new Person('Choi', 28);
console.log(student1);
console.log(student2);
console.log(student1.name);
console.log(student2.age);