[TS] public, protected, private, readonly

cabbage·2023년 1월 28일

TS

목록 보기
2/4
post-thumbnail

접근 제어자

타입스크립트에는 클래스의 특정 메서드나 속성이 클래스 외부 코드에 표시되는지 여부를 제어할 수 있는 접근 제어자인 public, protected, private이 존재한다.

public

public 은 클래스 멤버의 기본적인 접근 제어자이다. public 멤버는 클래스 외부 코드 어디서든지 접근 가능하다.

class Greeter {
  public greet() {  // public 생략 가능
  	console.log("안녕하세요!");
  }
}
const greeter = new Greeter();
greeter.greet();  // 안녕하세요!
  • public은 디폴트이므로 반드시 작성할 필요는 없다.
  • 코드 스타일이나 가독성을 위해 작성해도 된다.

protected

protected로 선언한 클래스 멤버의 경우 protected를 선언한 클래스와 해당 클래스의 서브클래스 내부에서만 사용할 수 있다.

class Greeter {
  public greet() {
    console.log("안녕하세요! " + this.getName());
  }
  
  protected getName() {
  	return "protected입니다";
  }
}

// Greet 클래스 상속
class SpecialGreeter extends Greeter {
  public howdy() {
    // 여기에선 protected 멤버에 접근할 수 있다.
    console.log("안녕하세요?? " + this.getName());
  }
}

const greeter = new SpecialGreeter();
greeter.greet();  // 안녕하세요! protected입니다.
greeter.howdy();  // 안녕하세요?? protected입니다.
greeter.getName();  // 에러
  • getName 메서드는 protected 멤버이므로 해당 클래스와 서브클래스 내부에서만 접근 가능하다.

private

private로 선언한 클래스 멤버의 경우 private을 선언한 클래스 내부에서만 접근 가능하다.

  • 서브클래스에서 슈퍼클래스의 private 멤버에 접근할 수 없다.
  • private을 선언한 클래스 외부에서도 접근할 수 없다.
class Base {
  private x = 0;
}

class Derived extends Base {
  getX() {
    // 서브클래스에서 private 멤버에 접근할 수 없다.
    return this.x;  // 에러
  }
}

const base = new Base();
console.log(base.x);  // 에러
  • x 변수는 private 멤버이므로 해당 클래스 내부에서만 접근 가능하다.

readonly

readonlyreadonly가 선언된 멤버를 생성자 바깥에서 수정할 수 없게 한다.

  • readonly 라는 이름에서도 알 수 있듯이 값을 읽을 수만 있고, 값을 쓸 수는 없다는 의미이다.
class IPhone {
  readonly name: string;
  
  constructor(name: string) {
    this.name = name;
  }

  setName(name: string) {
    this.name = name;  // 에러
  }
}

const iPhone = new IPhone("아이폰13");
console.log(iPhone.name);  // 아이폰13
apple.name = "아이폰13"; // 에러
  • name 변수는 readonly로 선언되어 있기 때문에 클래스 내부일지라도 생성자 바깥에서 수정할 수 없다.
  • 또한 클래스 외부에서도 수정할 수 없다.

public, protected, private, readonly로 변수 선언 생략하기

public, protected, private, readonly를 생성자의 매개변수에 선언하면 클래스 내부에서 변수 선언을 생략할 수 있고, 생성자에서도 매개변수를 할당하지 않아도 된다.

class Base {
  constructor(public x: number) {}
}

const base = new Base(1);
console.log(base.x);  // 1
class Base {
  constructor(protected x: number) {}

  getX() {
    return this.x;
  }
}

const base = new Base(1);
console.log(base.getX());  // 1
class Base {
  constructor(private x: number) {}

  getX() {
    return this.x;
  }
}

const base = new Base(1);
console.log(base.getX());  // 1
class Base {
  constructor(readonly x: number) {}

  getX() {
    return this.x;
  }
}

const base = new Base(1);
console.log(base.getX());  // 1

참고

profile
캐비지 개발 블로그입니다. :)

0개의 댓글