Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

developer_kcm

타입스크립트 문법 (접근 제어자) 본문

Typescript

타입스크립트 문법 (접근 제어자)

fullkeem 2024. 6. 3. 17:45

접근 제어자(Access Modifiers)

public -  어디서나 자유롭게 접근 가능, 클래스 바디에서 생략 가능

protected - 나와 파생된 후손 클래스 내에서 접근 가능

private - 내 클래스에서만 접근 가능

class UserA {
    first: string; // 생략된 public 
    protected last: string;
    private age: number;
    // private으로 접근 제어된 속성은 해당 클래스 밖에서는 age 속성을 조회하는 것도 불가능

// 매개변수 자리에서 접근 제어가 사용 가능.(단, 매개변수에서는 public 생략 x)
    constructor(
    	public first: string = '', 
        protected last: string = '', 
        private age: number = 0 ) {
        // this.first = first;
        // this.last = last;
        // this.age = age;
    }
// 접근 제어자는 속성에서만 쓰이지 않고 매서드에서도 사용 가능하다.
    protected getAge(): string {
        return `${this.first} ${this.last} is ${this.age}`;
    }
}


class UserB extends UserA {
    getAge(): string {
        return `${this.first} ${this.last} is ${this.age}`;
    }
}

class UserC extends UserB {
    getAge(): string {
        return `${this.first} ${this.last} is ${this.age}`;
    }
}

const neo = new UserA('Neo', 'Anderson', 102);
console.log(neo.first); // 'Neo'
console.log(neo.last);  // 'Anderson' 
// User A에서 last는 보호된 속성이므로, 클래스 내부 혹은 파생된 하위 클래스가 아니면 에러가 발생
console.log(neo.age);   // 102

 

타입스크립트에서 클래스는 객체 지향 프로그래밍의 기본 개념을 지원하며, 코드의 구조화와 재사용성을 높이는데 유용함.

클래스의 구성 요소들의 기능을 통해 강력하면서 유연한 클래스 기반 코드를 작성할 수 있을 것이다.

'Typescript' 카테고리의 다른 글

tsconfig.json 구성 옵션  (0) 2024.06.10
타입스크립트 문법 (함수)  (0) 2024.06.02
타입스크립트 문법 (Interface, Alias)  (0) 2024.06.01
타입스크립트 문법 (타입)  (0) 2024.05.30