ES6 ClassesJavascript2024. 9. 4. 04:21
Table of Contents
728x90
반응형
ES6에 나온 Class를 사용하여 더 쉽게 OOP를 구현할 수 있다.
이것은 문법을 OOP 방식을 사용하지만 내부에서 prototype을 사용하여 작동한다.

생성자 함수로 객체를 만들었을 때는
생성자 함수에 넣어둔 메소드가 인스턴스 객체 자체에 포함되어 있었지만,
Class의 경우 Class 안에 넣어둔 메소드가 바로 프로토타입에 들어가게 된다.
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@abc.com", "7-10-91");
console.log(john);
// Person {name: 'john', email: 'john@abc.com', birthday: Wed Jul 10 1991 00:00:00 GMT+0900 (한국 표준시)}
// [[Prototype]] : Object constructor : Class Person introduce : introduce()

- Static 사용.
"prototype"이 아닌 Class 함수 자체에 메소드를 설정할 수도 있다.
이런 메소드를 정적(static) 메소드라고 부른다.
this.name 같은 것을 안 쓰는 독립적인 것을 정의할 때 static을 사용하며
이 static 메서드를 사용할 때는 인스턴스가 아닌 Class 이름을 이용해서 사용한다.
=> 객체에도 없고, 프로토타입에도 들어가지 않는다.
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;
}
}
console.log(Person.multipleNumbers(2, 9)); // 18
static 메소드의 경우 이곳에 들어가게 된다.
프로토타입 내부의 constructor 내부에 위치하고 있다.

728x90
반응형
'Javascript' 카테고리의 다른 글
| super() (0) | 2024.09.04 |
|---|---|
| Sub Class(Inheritance) (0) | 2024.09.04 |
| javascript prototype (0) | 2024.09.04 |
| OOP(Object-oriented-programming) (0) | 2024.09.03 |
| Event 종류 (0) | 2024.09.03 |
@min' :: 개발을 하자
github : https://github.com/dnjfht
포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!