Access Modifiers

kukudas·2022년 2월 8일
0

TypeScript

목록 보기
18/39

접근 제어자는 클래스의 property와 method들의 접근 권한을 바꿔줌. 타입스크립트는 priavate, protected, public 3가지를 제공함.

타입스크립트는 런타임때 접근 권한을 제어하는게 아니라 컴파일 할때 logical 하게 제어함.

The private modifier

private은 클래스 안에서만 보이도록 바꿔줌. private을 property나 method에 붙일 경우에 그 property나 method는 같은 클래스 안에서만 접근가능해짐. 클래스 바깥에서 접근 시도할 경우 컴파일 할때 에러나옴.

class Person {
    private ssn: string;
    private firstName: string;
    private lastName: string;

	// private 설정한 거는 constructor나 클래스 안의 method에서 접근가능함.
    constructor(ssn: string, firstName: string, lastName: string) {
        this.ssn = ssn;
        this.firstName = firstName;
        this.lastName = lastName;
    }

    getFullName(): string {
        return `${this.firstName} ${this.lastName}`; 
    }
}

ssn propoerty를 클래스 바깥에서 접근 하려고 하면 에러나옴.

let person = new Person('153-07-3130', 'John', 'Doe');
console.log(person.ssn); // compile error

The protected modifier

protected는 property와 method를 같은 클래스 그리고 subclass에서 접근 가능하게해줌. 클래스가 다른 클래스를 상속하면 subclass라고함.
아래처럼 protected 키워드를 사용하면됨.

class Person {

    protected ssn: string;
    
    // other code
}

아래의 Person 클래스는 2개의 private property와 1개의 protected property를 선언했는데 생성자를 사용해서 property들을 초기화 했음. 타입스크립트에서 생성자를 통해서 property를 선언하고 초기화해서 코드를 줄일 수 있음.

class Person {
    constructor(protected ssn: string, private firstName: string, private lastName: string) {
        this.ssn = ssn;
        this.firstName = firstName;
        this.lastName = lastName;
    }

    getFullName(): string {
        return `${this.firstName} ${this.lastName}`;
    }
}
  • 타입스크립트는 private, protected, public 3가지의 access modifier를 제공함.
  • private modifier는 같은 클래스 안에서만 접근가능함
  • protected modifier는 같은 클래스 및 서브 클래스 안에서만 접근가능함
  • public modifier는 아무데서나 접근 가능함

출처

0개의 댓글

관련 채용 정보