TypeScript(12)

조은형·2023년 10월 20일

public

class User {
  public name: string;

  constructor(){
    this.name = 'kim';
  }
}

let 유저1 = new User();
유저1.name = 'park';

public이 붙은 속성은 자식 object들이 마음대로 사용하고 수정도 가능하다.
사실 public은 굳이 안 붙여도 된다.
왜냐하면 이미 안보이게 붙어있기 때문이다.

private

class User {
  public name :string;
  private familyName :string;  

  constructor(){
    this.name = 'kim';
    let hello = this.familyName + '안뇽'; //가능
  }
}

let 유저1 = new User();
유저1.name = 'park';  //가능
유저1.familyName = 456;

private는 class 내에서만 사용가능하다.
예를 들어서 familyName처럼 성을 바꿀 수 없기 때문에 private를 붙여서 못 바꾸게 하면된다.

protected

class User {
  protected x = 10;
}

class NewUser extends User {
  doThis(){
    this.x = 20;
  }
}

protected는 private보다 좀 덜 엄격하다.
extends로 상속을 받으면 private는 사용 할 수 없지만, protected는 사용할 수 있다.
물론 private와 protected 둘다 가지고는 있다.

static

class User {
  static x = 10;
  y = 20;
}

let john = new User();
john.x //불가능
User.x //가능

static들은 보통 class안에 간단한 메모를 하거나, 기본 설정값을 입력하거나, class로부터 생성되는 object가 사용할 필요가 없는 변수들을 만들어놓고 싶을 때 사용한다.

사실 나는 왜 있는지 잘 모르겠다.

profile
좋은 형

0개의 댓글