Notice
Recent Posts
Recent Comments
Link
관리 메뉴

윤일무이

[TypeScript] 접근 제어자 본문

❔ TypeScript/💭 한 입 크기 TypeScript

[TypeScript] 접근 제어자

썸머몽 2023. 12. 21. 01:24
728x90

접근 제어자(Access Modifier)

  • 클래스의 특정 필드나 메서드에 접근할 수 있는 범위를 설정하는 기능
  • TS에는 pubilc(모든 범위에서 가능), private(클래스 내부에서만 가능), protected(클래스/파생 클래스 내부에서만 가능)이 있다.

public

class Employee {
  // 필드
  name: string;      // 자동으로 public
  age: number;       // 자동으로 public
  position: string;  // 자동으로 public

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

  // 메서드
  work() {
    console.log("일함");
  }
}

const employee = new Employee("summermong", 27, "devloper");

employee.name = "wintermong";
employee.age = 30;
employee.position = "디자이너";
  • 별도로 설정하지 않으면 기본적으로 public 접근자를 갖게 된다.
  • 따라서 클래스 내부와 외부 모두 접근이 가능해 맨 아래와 같이 name, age, position을 모두 바꿔버릴 수 있다.
  • 필드에 직접적으로 접근 제어자를 명시할 수도 있다. (public name: string;)

private

class Employee {
  // 필드
  private name: string; // private 접근 제어자 설정
  public age: number;
  public position: string;

  ...

  // 메서드
  work() {
    console.log(`${this.name}이 일함`); // 여기서는 접근 가능
  }
}

const employee = new Employee("summermong", 27, "devloper");

employee.name = "wintermong"; // ❌ 오류
employee.age = 30;
employee.position = "디자이너";
  • private로 설정했기 때문에 클래스 내부인 메서드에서는 접근할 수 있다.
  • 반면 아까처럼 name을 바꾸려고 하면 name에 private 접근 제어자가 설정되어 있어 접근할 수 없다.

protected

class Employee {
  // 필드
  private name: string; // private 접근 제어자 설정
  protected age: number;
  public position: string;

  ...

  // 메서드
  work() {
    console.log(`${this.name}이 일함`); // 여기서는 접근 가능
  }
}

class ExecutiveOfficer extends Employee {
 // 메서드
  func() {
    this.name; // ❌ 오류 
    this.age; // ✅ 가능
  }
}

const employee = new Employee("summermong", 27, "devloper");

employee.name = "wintermong"; // ❌ 오류
employee.age = 30; // ❌ 오류
employee.position = "디자이너";
  • protected 접근 제어자는 클래스 외부에서는 접근할 수 없지만 내부와 파생 클래스에서는 접근이 가능하다.
  • protected age가 설정되어 있기 때문에 파생 클래스인 ExecutiveOfficer에서는 접근할 수 있지만 외부에서는 접근할 수 없다.
  • 위 예제에는 private name도 설정되어 있어서 오류가 같이 발생한다.

필드 생략

class Employee {
  // 필드
  private name: string;    // ❌
  protected age: number;   // ❌
  public position: string; // ❌

  // 생성자
  constructor(
    private name: string,
    protected age: number,
    public position: string
  ) {
    this.name = name; // 생략 가능
    this.age = age; // 생략 가능
    this.position = position; // 생략 가능
  }

  // 메서드
  work() {
    console.log(`${this.name} 일함`);
  }
}
  • 생성자의 매개변수에도 접근 제어자를 설정할 수 있다.
  • 이 때 동명의 필드를 선언하면 '중복'되었다고 한다.
  • 생성자의 매개변수에 접근 제어자를 설정하면 자동으로 필드도 선언되기 때문에 동명의 필드를 생략할 수 있다.
  • 또 접근 제어자가 설정된 매개변수는 [this.필드 = 매개변수] 가 자동으로 수행되기 때문에 생성자 내부에서 생략할 수 있다.
  • 이렇게 하면 코드를 더 간결하고 빠르게 작성할 수 있기 때문에 생략하는 것이 좋다.

 


 

 **출처: 한 입 크기로 잘라먹는 타입스크립트 (인프런, 이정환 강사님) 

728x90