constructor 함수와 prototype inheritance로 클래스 만들 수 있음.
ssn, firstName, lastName 이렇게 3개의 property를 가지는 Person
클래스를 만들고 싶으면 아래의 constructor 함수를 사용하면 됨.
function Person(ssn, firstName, lastName) {
this.ssn = ssn;
this.firstName = firstName;
this.lastName = lastName;
}
다음으로 prototype method를 정의해서 firstName이랑 lastName을 합쳐서 리턴해주는 method를 만들 수 있음.
Person.prototype.getFullName = function () {
return `${this.firstName} ${this.lastName}`;
}
이제 person class를 새 obejct를 만들어서 사용할 수 있음.
let person = new Person('171-28-0926','John','Doe');
console.log(person.getFullName());
아래처럼 class를 정의할 수 있는데 constructor functino과 prototypal inheritance의 syntactic sugar임.
class Person {
ssn;
firstName;
lastName;
constructor(ssn, firstName, lastName) {
this.ssn = ssn;
this.firstName = firstName;
this.lastName = lastName;
}
// method
getFullName() {
return `${this.firstName} ${this.lastName}`;
}
}
위처럼 클래스 정의하고 아래처럼 사용하면 됨.
let person = new Person('171-28-0926','John','Doe');
console.log(person.getFullName());
타입스크립트는 클래스의 property와 method에 type을 지정해 줄 수 있음.
아래는 Person
클래스를 타입스크립트로 만든거임.
class Person {
ssn: string;
firstName: string;
lastName: string;
constructor(ssn: string, firstName: string, lastName: string) {
this.ssn = ssn;
this.firstName = firstName;
this.lastName = lastName;
}
getFullName(): string {
return `${this.firstName} ${this.lastName}`;
}
}
class
키워드로 클래스 정의하기- 타입스크립트로 class안에 property와 method에 type 지정해줄 수 있어서 자바스크립트에 비해 좀 더 견고한 클래스 작성 가능함.