class2-Constructor & Initialize

홍인열·2021년 8월 11일
0

constructor & initialize

  • 생성자 함수가 없으면, 디폴트 생성자가 불린다.
  • 프로그래머가 만든 생성자가 하나라도 있으면, 디폴트 생성자는 사라진다.
  • strict 모드에서는 프로퍼티를 선언하는 곳 또는 생성자에서 값을 할당해야 한다.
  • 프로퍼티를 선언하는 곳 또는 생성자에서 값을 할당하지 않는 경우에는 !를 붙여서 위험을 표현한다.
  • 클래스의 프로퍼티가 정의되어 있지만, 값을 대입하지 않으면 undefined 이다.
  • 생성자에는 async를 설정할 수 없다.
    출처 : FastCampus__한 번에 끝내는 프론트엔드 개발 초격차 패키지 Online.
// constructor & initialize
class Person2 {
  name: string;
  age: number;
}
// defalut 생성자, 인자없이실행되는 constructor 함수 의미.
// 위의 상태에서 nmae과 age는 초기값이 미설정상태로 error를 야기.

---
class Person2 {
  name: string = "Hinyc";
  age: number;
}
// 이경우 default 생성자에 의해 함수 생성
const p1: Person2 = new Person2();
// 변수가 없지만 생성된 함수결과는 아래와 같다.
console.log(p1);
// => Person2 { name: 'Hinyc' }

---
class Person2 {
  name: string = "Hinyc";
  age: number;
  
  constructor (age: number) {
  	this.age = age;
  }
}
// constructord을 통해 변수 설정을 해주면 default 생성자에 의한 함수 생성 미실행.

---
// constructor을 설정하고, 변수 미지정 함수를 사용하고자 한다면
  class Person2 {
  name: string = "Hinyc";
  age: number;
  
  constructor (age?: number) {
  	if (age === undefined) {
    this.age = 20;
    } else {
    this.age = age;
    }
  }
}
// 이런식으로 if 함수를 적용할 수 있다.
// if함수 적용없이 변수 미지정 함수일 경우 class age: number기 때문에 error 발생.
const p21 = new Person2();
const p22 = new Person2(31);

console.log(p21);
// => Person2 { name: 'Hinyc', age: 20}
console.log(p22);
// => Person2 { name: 'Hinyc', age: 31}

profile
함께 일하고싶은 개발자

0개의 댓글