class Person {
name;
constructor(name: string) {
this.name = name;
}
}
const p1 = new Person('Tommy');
console.log(p1);
class Person {
name: string = "Tommy";
age: number;
constructor(age?: number) {
if (!age) {
this.age = 20;
} else {
this.age = age;
}
}
}
const p1: Person = new Person(39);
const p2: Person = new Person();
console.log(p1); // p1.age = 39;
console.log(p1.age); // 39;
→ 생성자의 파라미터를 받아서 그 클래스의 프로퍼티로 초기화 하는 방법
class Person {
public constructor(public name: string, private age: number) {
}
}
const p1: Person = new Person('Tommy', 26);
console.log(p1);
class Person {
public constructor(private _name: string, private age: number) {
}
// 얻어오기
get name() {
// return 필수
// console.log('get');
return this._name + 'Lee';
}
// 변경하기
set name(n: string) {
// 인자 필수
// console.log('set');
// count해서 몇번 set 되었는지 활용할 수도 있음
this._name = n;
}
const p1: Person = new Person('Tommy', 26);
console.log(p1.name); // getter 함수 적용
p1.name = 'Tommy'; // setter 함수 적용
console.log(p1.name);
class Person {
public readonly name: string = 'Tommy';
private readonly country: string;
constructor(private _name: string, private age: number) {
// constructor 안에서만 설정가능
this.country = 'Korea';
}
}
class Department {
// 정적 필드는 this로 접근이 불가능하다.
// 무조건 클래스 이름 + '.'과 함께 쓰여야 한다.
static fiscalYear = 2023;
constructor(protected readonly id: string, public name: string) {
}
static createEmployee(name: string) {
return { name: name };
}
}
// 정적 메서드를 사용하면 인스턴스를 만들지 않고도 바로 class method를 사용할 수 있다.
const employee1 = Department.createEmployee('Tommy');
console.log(employee1, Department.fiscalYear);
class AccountingDepartment extends Department {
private lastReport: string;
private static instance: AccountingDepartment;
private constructor(id: string, private reports: string[]) {
super(id, 'Accounting');
this.lastReport = reports[0];
}
static getInstance() {
// 생성자가 private 생성자이므로 클래스 선언 내부에서 instance가 있으면 기존 인스턴스를 내보내고
// 인스턴스가 없으면 새로운 인스턴스를 생성하여 내보낸다.
if (AccountingDepartment.instance) {
return this.instance;
}
this.instance = new AccountingDepartment('d2', []);
return this.instance;
}
}
...
const accounting = AccountingDepartment.getInstacne();
// 이미 기존 인스턴스 accounting이 있으므로 accounting2는 이전의 값으로 반환된다.
const accounting2 = AccountingDepartment.getInstacne();
class ITDepartment extends Department {
admins: string[];
constructor(id: string, admins: string[]) {
// super 호출을 통해 기존 Department 클래스 생성자 호출
super(id, 'IT');
this.admins = admins;
}
}
abstract class Department {
protected employees: string[] = [];
constructor(protected readonly id: string, public name: string) {
}
// 추상 클래스의 추상 메소드
abstract describe(this: Department): void;
}
...
class AccountingDepartment extends Department {
...
// 상속받는 클래스에서 추상 메서드에 대한 구체적인 기술
describe() {
console.log('Accouning Department - ID: ' + this.id);
}