티스토리 뷰

🍊 접근 제어자

Access Modifier

타입스크립트에서만 제공되는 기능으로 클래스의 특정 필드나 메소드에 접근할 수 있는 범위를 설정하는 기능이다.

3개의 접근 제어자

  • public : 모든 범위에서 접근 가능
  • private : 클래스 내부에서만 접근 가능
  • protected : 클래스 내부 또는 파생 클래스 내부에서만 접근 가능

 

 

 

🍊 public

어디서든지 해당 프로퍼티에 접근할 수 있음을 의미히며 필드의 접근 제어자를 지정하지 않을 경우 기본값으로 설정된다.

class Employee {
  // 필드
  name: string;      // 자동으로 public
  age: number;       // 자동으로 public
  public 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, 'developer');
employee.name = '기지';
employee.age = 20;
employee.position = 'designer';

 

 

 

 

 

🍊 private

클래스 내부에서만 해당 필드에 접근할 수 있으며  클래스 외부와 파생 클래스 내부에서 접근이 불가능하다.

class Employee {
    // 필드
    // 앞에는 public이 기본값으로 등록되어 있음 
    // public (공공의) -> 어디서든 프로퍼티에 접근이 가능
    public name: string;
    // private (제한된) -> 클래스 내부에서만 접근이 가능
    private age: number;
    public position: string;

    // 생성자
    constructor(name: string, age: number, position: string){
        this.name = name;
        this.age = age;
        this.position = position;
    }
    
    // 메소드
    work(){
        // private한 프로퍼티는 클래스 내부에서만 접근 가능
        console.log(`${this.name} 일함`)
    }
}

// 파생 클래스 내에서도 private한 프로퍼티는 접근이 불가능
class ExecutiveOfficer extends Employee {
    // 필드
    officeNumber: number;

    // 생성자
    constructor(name: string, age: number, position: string, officeNumber: number){
       super(name, age, position);
       this.officeNumber = officeNumber; 
    }

    // 메소드
    func(){
        // private
        this.age; // ❌ 
    }
}

const employee = new Employee('김기지', 27, 'developer');
employee.name = '기지';
employee.age = 20; // ❌
employee.position = 'designer';

 

 

 

 

 

 

🍊 protected

클래스 외부에서는 접근이 불가능하지만 클래스 내부와 파생 클래스에서는 접근이 가능하다.

class Employee {
    // 필드
    // 앞에는 public이 기본값으로 등록되어 있음 
    // public (공공의) -> 어디서든 프로퍼티에 접근이 가능
    public name: string;
    // private (제한된) -> 클래스 내부에서만 접근이 가능
    private age: number;
    // protected (보호된) -> 클래스 외부에서는 접근이 안되지만 클래스 내부와 파생 클래스에서 접근이 가능
    protected position: string;

    // 생성자
    constructor(name: string, age: number, position: string){
        this.name = name;
        this.age = age;
        this.position = position;
    }
    
    // 메소드
    work(){
        // private한 프로퍼티는 클래스 내부에서만 접근 가능
        console.log(`${this.name} 일함`)
    }
}

// 파생 클래스 내에서도 private한 프로퍼티는 접근이 불가능
// 파생 클래스 내에서만 접근이 가능하도록 하는 경우에는
// protected 접근자로 설정
class ExecutiveOfficer extends Employee {
    // 필드
    officeNumber: number;

    // 생성자
    constructor(name: string, age: number, position: string, officeNumber: number){
       super(name, age, position);
       this.officeNumber = officeNumber; 
    }

    // 메소드
    func(){
        // private
        this.age; // ❌
        // protected
        this.position; // ✅
    }
}

const employee = new Employee('김기지', 27, 'developer');
employee.name = '기지';
employee.age = 20; // ❌
employee.position = 'designer'; // ❌

 

 

 

 

 

🍊 필드 생략하기

접근 제어자를 생성자의 매개변수에 설정하는 경우 필드를 자동으로 생성하기 때문에 필드의 생략이 가능하다.

class Employee {
    // 필드
    // 생성자의 매개변수에 접근 제어자를 설정 -> 필드 생략 가능
	name; // ❌ -> 접근 제어자가 설정된 매개변수와 동일한 이름의 필드 선언 불가능
    // 생성자
    // 생성자에 접근 제어자를 명시하는 경우 
    // 자동으로 필드가 생성됨
    constructor(public name: string, private age: number, protected position: string){
        this.name = name;
        this.age = age;
        this.position = position;
    }
    
    // 메소드
    work(){
        // private한 프로퍼티는 클래스 내부에서만 접근 가능
        console.log(`${this.name} 일함`)
    }
}

const employee = new Employee('김기지', 27, 'developer');
employee.name = '기지';

 

생성자 매개변수에 접근 제어자가 설정되면 자동으로 필드가 함께 선언되기 때문에 동일한 이름의 필드를 선언하지 못한다.

 

또, 접근 제어자가 설정된 매개변수들은 this.필드 = 매개변수 가 자동으로 수행되므로 생성자 내부의 코드를 제거해도 된다.

class Employee {
    // 필드
    
    // 생성자
    // 생성자에 접근 제어자를 명시하는 경우 
    // 자동으로 필드가 생성됨
    constructor(public name: string, private age: number, protected position: string){
        // 접근 제어자가 설정된 매개변수들은 this.필드 = 매개변수 가 자동으로 수행됨
        // -> 생성자 내부 코드 제거 가능
    }
    
    // 메소드
    work(){
        // private한 프로퍼티는 클래스 내부에서만 접근 가능
        console.log(`${this.name} 일함`)
    }
}

employee를 콘솔창에 찍어보면

 

 

타입스크립트에서 클래스를 사용할 때에는 보통 생성자 매개변수에 접근 제어자를 설정하여 필드 선언과 생성자 내부 코드를 생략하는 것이 훨씬 간결하고 빠르게 코드를 작성할 수 있다.

 

 

 


🔗 타입스크립트 강의

 

한 입 크기로 잘라먹는 타입스크립트(TypeScript) - 인프런 | 강의

문법을 넘어 동작 원리와 개념 이해까지 배워도 배워도 헷갈리는 타입스크립트 이제 제대로 배워보세요! 여러분을 타입스크립트 마법사🧙🏻‍♀️로 만들어드립니다., 프론트엔드의 피할 수

www.inflearn.com

 

728x90