TS에서는 클래스(class) 내에서 속성 및 메서드의 접근 범위를 조정하기 위해 접근 제한자 사용
1. Private - 클래스 내부에서만 접근 가능
2. Protected - 클래스 내부 + 자식 클래스에서 접근 가능
3. Public - 어디서든 접근 가능
class Post {
public title: string; // 공개 속성
constructor(title: string) {
this.title = title;
}
public getTitle() {
return this.title; // 어디서든 접근 가능
}
}
const post = new Post("TypeScript 접근제한자");
console.log(post.title); // ✅ 접근 가능
console.log(post.getTitle()); // ✅ 접근 가능
class Post {
private content: string; // 비공개 속성
constructor(content: string) {
this.content = content;
}
private getContent() {
return this.content;
}
public printContent() {
console.log(this.getContent()); // ✅ 내부에서 호출 가능
}
}
const post = new Post("비공개 게시글 내용");
console.log(post.content); // ❌ 오류 (private 속성 접근 불가)
console.log(post.getContent()); // ❌ 오류 (private 메서드 접근 불가)
post.printContent(); // ✅ 내부 메서드를 통해 접근 가능
class Post {
protected category: string; // 보호된 속성
constructor(category: string) {
this.category = category;
}
}
class TechPost extends Post {
constructor(category: string) {
super(category);
}
public getCategory() {
return this.category; // ✅ 자식 클래스에서 접근 가능
}
}
const techPost = new TechPost("TypeScript");
console.log(techPost.getCategory()); // ✅ 가능 (자식 클래스에서 접근)
console.log(techPost.category); // ❌ 오류 (외부에서 접근 불가)
접근 제한자 | 클래스 내부 | 자식 클래스 | 클래스 외부 |
---|---|---|---|
public | ✅ | ✅ | ✅ |
private | ✅ | ❌ | ❌ |
protected | ✅ | ✅ | ❌ |