목차
1. private
2. protected
3. public
1. private
- 해당 클래스 내부에서만 접근할 수 있게 하는 제어자
class Person {
private name: string;
constructor(name: string) {
this.name = name;
}
}
const person = new Person('홍길동');
console.log(person.name);
console.log에 person의 name을 출력하는 부분에서 접근불가하다는 에러가 발생한다.
2. protected
- 해당 클래스 및 하위 클래스에서 속성에 접근할 수 있게 하는 제어자
class Person {
protected name: string;
constructor(name: string) {
this.name = name;
}
}
const person = new Person('홍길동');
console.log(person.name);
private과 마찬가지로 console.log에 person의 name을 출력하는 부분에서 접근불가하다는 에러가 발생한다.
그런데 private과 에러의 내용이 다르게 하위 클래스에서 접근이 가능하다는 말이 포함되어 있다.
protected의 경우 외부에서는 속성에 접근할 수 없지만 상속받은 자식 클래스에서 부모클래스의 접근 제어자가 있는 속성에 접근할 수 있다. 그러나 private의 경우에는 자식클래스에서도 접근제어자가 있는 부모클래스 속성에 접근을 할 수가 없다.
3. public
- 외부에서 접근이 가능한 접근 제어자
public의 경우 외부에서 접근이 가능하게 허가하는 것이기 때문에 객체지향의 캡슐화에 위배되는 것이기에 되도록 사용하는 것을 권장하지 않는다. 직접적인 내부 속성이 아닌 외부에서 접근할 수 있도록 getter/setter에 지정하는 것이 좋다.
class Person{
public name:string;
constructor(name:string){
this.name = name;
}
}
const person = new Person('홍길동');
console.log(person.name);
/*
결과
홍길동
*/
'JS > 타입스크립트' 카테고리의 다른 글
객체 타입체크 (0) | 2024.05.02 |
---|---|
동적언어를 정적으로 사용하기! 타입스크립트 (0) | 2024.04.25 |