프론트엔드 개발/Typescript

private / public 액세스 수정자, 약식 초기화, readonly

하이고니 2023. 2. 21. 23:43

private / public


Department라는 클래스를 만들어보자.

 

Department는

 

name, employees라는 프로퍼티를 가지고 있고,

부서 이름을 출력하는 describe 메서드와 employee를 추가할 수 있는 addEmployee라는 메서드를 포함한다.

 

마지막에 있는 printEmployeeInformation 메서드는 employees 배열의 정보를 출력한다.

 

class Department {
  name: string;
  employees: string[] = []; 

  constructor(n: string) {
    this.name = n;
  }
  
  describe(this: Department) {
    console.log('Department: ' + this.name);
  }

  addEmployee(employee: string) {
    this.employees.push(employee);
  }
  
  printEmployeeInformation() {
    console.log(this.employees.length);
    console.log(this.employees);
  }
}

const accounting = new Department('Accounting');

accounting.addEmployee('Max');
accounting.addEmployee('Manu');

accounting.printEmployeeInformation();

 

 

addEmplyee를 실행하고 print한 결과

 

이 클래스에는 문제가 하나 있다. 바로 'employees'를 외부에서 변경할 수 있다는 것이다.

 

accounting.employees[2] = 'Anna';

 

외부에서 클래스 내부의 프로퍼티를 수정한 상황

 

복잡한 애플리케이션을 구축할 때, 이런 상황은 피해야 한다.

클래스를 사용할 수 있는 방법은 한 가지로 정해두고, 다른 방법은 사용하지 않도록 해야 한다.

 

큰 팀에서 일하면서 각 팀이 클래스의 프로퍼티에 접근하는 방식을 다르게 취한다면, 혼란을 빚을 수 있다.

가장 정확한 방법은 외부에서 클래스의 내부에 접근하지 못하도록 하는 것이다. 타입스크립트가 그 역할을 수행할 수 있다.

 

 

프로퍼티 앞에 private 키워드를 붙이는 방법이 바로 그것이다.

private 키워드를 프로퍼티 앞에 붙이면, 외부에서 그 프로퍼티에 접근할 수 없게 된다.

 

에러가 발생하는 것을 볼 수 있다.

 

이 private 키워드를 '제어자'라고 한다.

 

반대 개념으로 public이 존재하는데 이건 디폴트값이라서 굳이 써줄 필요가 없다. public 프로퍼티는 외부에서 접근이 가능하다.

자바스크립트는 public과 private의 개념을 모른다. 가장 최신 버전에 이르러서 추가되었고, 예전에는 자바스크립트에서 모든 프로퍼티는 public이었다. 그래서 같은 코드를 자바스크립트에서 사용한다면 에러가 발생하지 않을 수도 있다.

 

 

약식 초기화


뒤가 생략된 코드임

 

클래스를 선언할 때 위와 같이 프로퍼티가 많다면 처리해야할 코드 또한 길어진다. (이중)

이것을 축약할 수 있다.

 

 

생성자가 취할 인자를 정의하면 접근 제어자(private)를 지닌 모든 인자에 대해 동일한 이름의 프로퍼티가 생성되고,

인자에 대한 값이 생성된 그 프로퍼티에 저장되는 것이다.

 

 

코드

 

class Department {
  private employees: string[] = []; 

  constructor(private id: string, private name: string) {
  }
  
  describe(this: Department) {
    console.log(`Department (${this.id}): ${this.name}`);
  }

  addEmployee(employee: string) {
    this.employees.push(employee);
  }
  
  printEmployeeInformation() {
    console.log(this.employees.length);
    console.log(this.employees);
  }
}

const accounting = new Department('d1', 'Accounting');	// id, name 입력
accounting.describe();

 

출력된 내용

 

 

위와 같이 readonly를 추가해 안정성을 높일 수도 있다.