본문 바로가기
✘✘✘ Javascript/Typescript

Constructor overloading with default

by PrettyLog 2022. 6. 25.

변수 선언 후 생성자에서 할당

class Test {
  name: string;
  protected age: number;
  public id?: string;
  private password?: string;

  constructor(name = "", age = 0, id = undefined, password = undefined) {
    this.name = name;
    this.age = age;
    this.id = id;
    this.password = password;
  }
}

생성자에서 선언하고 변수 할당하기 => id, password

class Test {
  name: string;
  protected age: number;

  constructor(
    name: string = "",
    age: number = 0,
    public id?: string,
    private password?: string
  ) {
    this.name = name;
    this.age = age;
  }
}

생성자 overloading multitple constructor with default one

class Test {
  name: string;
  protected age: number;

  constructor();
  constructor(name: string);
  constructor(age: number);// Error!! parameter sequence must be same
  constructor(name: string, age: number);
  constructor(name: string, age: number, id: string);
  constructor(name: string, age: number, id: string, password?: string);
  constructor(name: string, age: number, id: string, password?: string);
  constructor(
    name: string = "",
    age: number = 0,
    public id?: string,
    private password?: string
  ) {
    this.name = name;
    this.age = age;
  }
}

댓글