ES6에서 나온 Class를 이용해서 더 쉽게 OOP을 구현할 수 있습니다.
이것은 문법을 OOP 방식을 이용하지만 내부에서 prototype을 사용하며 작동됩니다.
class Person {
constructor(name, email, birthday){
this.name = name;
this.email = email;
this.birthday = new Date(birthday);
}
introduce() {
return `hello my name is ${this.name}`;
}
}
const john = new Person('john', 'john@example.com', '7-10-91');
console.log(john);
클래스 안에 함수를 만들면 그 함수가 바로 prototype에 들어가게 된다.
Static 사용
"prototype"이 아닌 클래스 함수 자체에 메서드를 사용할 수도 있습니다. 이런 메서드를 정적(static) 메서드라고 부릅니다.
this.name 같은 것을 안 쓰는 독립적인 것을 정의할 때 static을 사용하며 static 메서드를 사용할 때는 인스턴스가 아닌 클래스 이름을 이용해서 사용합니다.
class Person {
constructor(name, email, birthday){
this.name = name;
this.email = email;
this.birthday = new Date(birthday);
}
introduce() {
return `hello my name is ${this.name}`;
}
static multipleNumbers(x,y) {
return x*y;
}
}
const john = new Person('john', 'john@example.com', '7-10-91');
console.log(john);