
클래스 내부의 특정 메서드나 프로퍼티를 클래스 외부에서 컨트롤할 수 있는지를 제어
public: 어디서나 접근 가능(default)
protected:상속받은 하위클래스까지만 접근 가능, 외부에서는 접근 불가능
private:선언한 클래스 내에서만 접근가능
타입스크립트에서 public, private, protected는 접근 제한자(Access Modifiers)로, 클래스의 속성이나 메서드의 가시성을 제어하는 데 사용된다.
public : 이 접근 제한자는 클래스의 속성이나 메서드가 공용으로 사용될 수 있음을 의미한다. 즉, 클래스 인스턴스를 통해 외부에서 자유롭게 접근하거나 수정할 수 있습니다. 모든 클래스 멤버는 기본적으로 public 이다.typescriptCopy code
class Person {
public name: string;
constructor(name: string) {
this.name = name;
}
}
let john = new Person('John');
console.log(john.name); // "John", 외부에서 접근 가능
private : 이 접근 제한자는 클래스의 속성이나 메서드가 해당 클래스 내에서만 접근 가능함을 의미한다. 즉, 클래스 외부에서는 해당 멤버를 볼 수도, 접근할 수도 없다.typescriptCopy code
class Person {
private name: string;
constructor(name: string) {
this.name = name;
}
}
let john = new Person('John');
console.log(john.name); // 에러, private 멤버이므로 외부에서 접근 불가능
protected : 이 접근 제한자는 private과 유사하게 클래스의 속성이나 메서드가 해당 클래스와 하위 클래스 내에서만 접근 가능함을 의미한다.typescriptCopy code
class Person {
protected name: string;
constructor(name: string) {
this.name = name;
}
}
class Employee extends Person {
sayName() {
console.log(this.name); // "John", 부모 클래스의 protected 멤버에 접근 가능
}
}
let john = new Employee('John');
john.sayName();
이렇게 접근 제한자를 사용하면 클래스의 내부 구현을 캡슐화하고, 클래스를 사용하는 코드에서 클래스 멤버에 대한 접근을 제어할 수 있다. 이는 소프트웨어의 안정성을 높이고, 코드의 유지 보수를 쉽게 만드는 데 도움이 된다.