클래스 문법이란?
조금 더 자바스럽게, 객체 지향적으로 표현하기 위해 ES6버전부터 추가된 새로운 문법이다. 다만 생김새만 클래스 구조이고, 엔진 내부적으로는 프로토타입 방식으로 작동된다.
class Person{
constructor(name, email, birthday){
this.name = name;
this.email = email;
this.birthday = birthday;
}
introduce(){
return `Hello my name is ${this.name}`
}
}
const lee = new Person('Lee', 'Lee@example.com', '2000-01-01');
constructor
인스턴스를 생성하고 클래스 필드를 초기화하기 위한 특수한 메서드이다. constructor는 클래스 안에 한 개만 존재할 수 있다.
클래스에 new를 붙여서 인스턴스 객체로 생성하면, 넘겨받은 인수와 함께 constructor가 먼저 실행된다. 이때 넘겨받은 인수를 this.변수명에 할당된다.
const lee = new Person('Lee', 'Lee@example.com', '2000-01-01');
이 부분을 자세히 보면 다음과 같다.
1. 새로운 객체가 생성된다.
2. 넘겨받은 인수와 함께 constructor가 자동으로 실행된다.
3. 각 인수를 this를 통해 객체에 할당된다.
class의 메서드
생성자 함수에서는 메서드를 prototype에 넣기 위해서 [생성자함수명.prototype.메서드] 또는 Object.create() 메서드를 사용했었다. 하지만 es6 class 문법에서는 클래스 안에 함수를 만들면 바로 prototype에 들어간다.
static
‘prototype’이 아닌 클래스 함수 자체에 메서드를 설정할 때 사용한다. 이런 메서드를 정적(static) 메서드라고 한다.
this.name 같은 것을 안 쓰는 독립적인 것을 정의할 때 static을 사용하며, 이 static 메서드를 사용할 때는 인스턴스가 아니라 클래스 이름을 이용해서 사용한다.
class Person{
constructor(name, email, birthday){
this.name = name;
this.email = email;
this.birthday = birthday;
}
introduce(){
return `Hello my name is ${this.name}`
}
static mutiplyNumbers(x, y){
return x * y;
}
}
const lee = new Person('Lee', 'Lee@example.com', '2000-01-01');
static으로 생성된 mutiplyNumbers 메서드가 prototype가 아닌 class 안에 속해있음을 확인할 수 있다.
// console.log(lee.mutiplyNumbers()); 이거 아님
console.log(Person.mutiplyNumbers(2, 3)); // 6
따라서 다음과 같이 클래스 이름뒤에 메서드를 붙여서 사용하면 된다.
sub class
class Person {
constructor(name, email) {
this.name = name;
this.email = email;
}
introduce() {
return `Hello my name is ${this.name}`
}
}
class Client extends Person {
constructor(name, email, phone, address) {
super(name, email);
this.phone = phone;
this.address = address;
}
}
const lee = new Client('Lee', 'Lee@example.com', '010-0000-0000', 'Seoul');
extends 키워드를 통해 Client 클래스가 Person 클래스를 상속했다.
위와 같이 자식 클래스 A가 다른 클래스 B를 상속받으면, 자식 클래스 A를 통해 부모 클래스 B의 정적 메서드와 정적 속성을 사용할 수 있고, 부모 클래스 B의 인스턴스 메서드와 인스턴스 속성을 자식 클래스 A의 인스턴스에도 사용할 수 있다
lee.introduce() // 'Hello my name is Lee'
부모 클래스에 있던 introduce 메서드를 실행시켜도 잘 출력되는 것을 확인할 수 있다. 순서는 다음과 같다.
1. Client 객체에 Client.introduce가 있는지 확인한다.
2. 없기 때문에 Client.prototype에 있는지도 확인하지만 역시 없다.
3. extends를 통해 관계가 만들어진 Client.prototype의 프로토타입인 Person.prototype에 메서드가 있는지 확인한다.
4. introduce가 있는 것을 확인 후 사용한다.
super
1. 자식 클래스 내에서 부모 클래스의 생성자를 호출할 때 사용한다.
2. 자식 클래스 내에서 부모 클래스의 메서드를 호출할 때 사용한다.
'프로그래밍 언어 > JavaScript' 카테고리의 다른 글
[JS] Module Pattern (0) | 2024.05.01 |
---|---|
[JS] Prototype (0) | 2024.04.29 |
[JS] Callback, Promise, Async/Await (0) | 2024.04.29 |
[JS] 순수함수(Pure Function) (0) | 2024.04.29 |
[JS] Intersection observer (0) | 2024.04.27 |