TypeScript
[ts] 클래스 protected 프로퍼티에 관해서 알아보자.
유병각
2022. 7. 5. 10:14
안녕하세요. gaki 입니다.
오늘은 자바스크립트 클래스의 protected 에 관해서 다뤄보겠습니다.
A 라는 클래스에 protected 로 정의된 property 와 method 가 있다고 가정합시다.
그럼 A 라는 클래스 내부에서는 당연히 protected 로 정의된 것들에 접근할 수 있습니다.
하지만 외부에서는 A 라는 클래스 안에 protected 된 것들에 접근할 수 없습니다. 여기까지는 private 과 똑같은데요.
protected 와 private 의 차이점은, private 는 private 된 속성을 오직 해당 클래스 내부에서만 접근 할 수 있다는 점이지만,
protected 는 해당 속성을 해당 클래스 내부 + 자식 클래스 에서도 접근 할 수 있다는 점이 다릅니다.
class Person {
region: string;
name: string;
age: number;
protected time:string;
private _pri: number;
constructor(name, age, region) {
this.name = name;
this.age = age;
this.region = region;
this.time = "10:21";
this._pri = 10;
}
eat(food) {
console.log(`${this.name} is eating ${food}`);
}
get pri() {
return this._pri;
}
set pri(num:number) {
this._pri = num;
}
protected sleep() {
console.log(this.time);
console.log("sleep");
}
}
class Gak extends Person {
name: string;
age: number;
region: string;
h : number;
constructor(name, age, region, h) {
super(name, age, region);
this.h = h;
}
sleepp() {
this.sleep();
console.log(this.time);
}
}
const gak = new Gak("gak", 15, "seoul", 133);
// private property getter test
console.log(gak.pri);
// private property setter test
gak.pri = 1111;
console.log(gak.pri);
// protected method test on child class
gak.sleepp();
? private 속성을 getter 와 setter 를 통해 클래스 외부에서 변경 할 수 있는지 ? => 가능하다.