constructor & initialize
- 생성자 함수가 없으면, 디폴트 생성자가 불린다.
- 프로그래머가 만든 생성자가 하나라도 있으면, 디폴트 생성자는 사라진다.
- strict 모드에서는 프로퍼티를 선언하는 곳 또는 생성자에서 값을 할당해야 한다.
- 프로퍼티를 선언하는 곳 또는 생성자에서 값을 할당하지 않는 경우에는 !를 붙여서 위험을 표현한다.
- 클래스의 프로퍼티가 정의되어 있지만, 값을 대입하지 않으면 undefined 이다.
- 생성자에는 async를 설정할 수 없다.
출처 : FastCampus__한 번에 끝내는 프론트엔드 개발 초격차 패키지 Online.
class Person2 {
name: string;
age: number;
}
---
class Person2 {
name: string = "Hinyc";
age: number;
}
const p1: Person2 = new Person2();
console.log(p1);
---
class Person2 {
name: string = "Hinyc";
age: number;
constructor (age: number) {
this.age = age;
}
}
---
class Person2 {
name: string = "Hinyc";
age: number;
constructor (age?: number) {
if (age === undefined) {
this.age = 20;
} else {
this.age = age;
}
}
}
const p21 = new Person2();
const p22 = new Person2(31);
console.log(p21);
console.log(p22);