접근제어자
- 접근 제어자(Access Modifier)는 타입스크립트에서만 제공되는 기능으로
클래스의 특정 필드나 메서드를 접근할 수 있는 범위를 설정하는 기능입니다.
➡️ public : 모든 범위에서 접근 가능
class Employee {
public name: string;
age: number;
position: string;
constructor(name: string, age: number, position: string) {
this.name = name;
this.age = age;
this.position = position;
}
work() {
console.log("일함");
}
}
const employee = new Employee("이정환", 27, "devloper");
employee.name = "홍길동";
employee.age = 30;
employee.position = "디자이너";
➡️ private : 클래스 내부에서만 접근 가능
class Employee2 {
private name: string;
public age: number;
public position: string;
constructor(name: string, age: number, position: string) {
this.name = name;
this.age = age;
this.position = position;
}
work() {
console.log(`${this.name}이 일함`);
}
}
const employee2 = new Employee2("이정환", 27, "devloper");
employee2.age = 30;
employee2.position = "디자이너";
➡️ protected : 클래스 내부 또는 파생 클래스 내부에서만 접근 가능
class Employee3 {
private name: string;
protected age: number;
public position: string;
constructor(name: string, age: number, position: string) {
this.name = name;
this.age = age;
this.position = position;
}
work() {
console.log(`${this.name}이 일함`);
}
}
class ExecutiveOfficer extends Employee3 {
func() {
this.age;
}
}
const employee3 = new Employee3("이정환", 27, "devloper");
employee3.position = "디자이너";
➡️ 필드 생략하기
class Employee4 {
constructor(
private name: string,
protected age: number,
public position: string
) {
}
work() {
console.log(`${this.name} 일함`);
}
}