JavaScript&TypeScript

TypeScript Class 접근 제한자와 readonly

5kiran 2023. 1. 18.
반응형

Class의 선언

class Mozzi {
  readonly name : string = "아라"
  readonly boyFriend : string = "없음"
  constructor( boyFriend : string) {
    this.boyFriend = boyFriend
  }
  
  start() {
    console.log("2023.01.11 Start")
  }
}

Mozzi 라는 class를 정의한다

Mozzi.name = "아라"

Mozzi.boyFriend = "없음"

 

처음 정의한 Mozzi.boyFriend는 "없음"이지만 constructor을 통해 boyFriend를 주입해 줄 수 있다.

const 모찌 = new Mozzi("길환")

// 모찌.boyFriend를 외부에서 임의로 변경할 수 없다
모찌.boyFriend = "없음" //  readonly 속성이기 때문에 constructor를 통해서 주입하는게 아니라면 변경할 수 없다

 

접근 제한자(Access modifier) - public, private, protected

 

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

public - 자식 클래스, 클래스 인스턴스 모두 접근 가능

protected - 자식 클래스에서 접근 가능

 

private

해당 클래스 내부가 아니기 때문에 boyFriend 클래스에서 사용 불가

class Mozzi {
  private name : string = "아라"
  readonly boyFriend : string = "없음"
  constructor( boyFriend : string) {
    this.boyFriend = boyFriend
  }
  
  start() {
    console.log("2023.01.11 Start")
    console.log(this.name)
  }
}


class BoyFriend extends Mozzi {
  constructor(boyFriend : string) {
    super(boyFriend)
  }

  showBoyFriend() {
    console.log(`${super.name} Love ${super.boyFriend}`) //super.name에 private 속성이 걸려있어 자식 클래스에서 사용할 수 없음
  }
}

 

public 

자식클래스 클래스 인스턴스 모두 접근 가능

class Mozzi {
  public name : string = "아라"
  public boyFriend : string = "없음"
  constructor( boyFriend : string) {
    this.boyFriend = boyFriend
  }
  
  start() {
    console.log("2023.01.11 Start")
    console.log(this.name)
  }
}


class BoyFriend extends Mozzi {
  constructor(boyFriend : string) {
    super(boyFriend)
  }

  showBoyFriend() {
    console.log(`${super.name} Love ${super.boyFriend}`) //public 자식 클래스에서 접근 가능
  }
}

const 아라 = new BoyFriend("길환")
console.log(아라.name) // public 외부에서 접근 가능
console.log(아라.boyFriend) // public 외부에서 접근 가능

 

protected

자식 클래스에서 사용 가능 외부에서 접근 불가

class Mozzi {
  protected name : string = "아라"
  protected boyFriend : string = "없음"
  constructor( boyFriend : string) {
    this.boyFriend = boyFriend
  }
  
  start() {
    console.log("2023.01.11 Start")
    console.log(this.name)
  }
}


class BoyFriend extends Mozzi {
  constructor(boyFriend : string) {
    super(boyFriend)
  }

  showBoyFriend() {
    console.log(`${super.name} Love ${super.boyFriend}`) //protected 자식 클래스에서 접근 가능
  }
}

const 아라 = new BoyFriend("길환")
console.log(아라.name) // protected 외부에서 접근 불가
console.log(아라.boyFriend) // protected 외부에서 접근 불가
반응형

댓글