[JavaScript] ES6 Class
ES6(ECMAScript 2015)에서 도입된 class 문법은 기존의 프로토타입 기반 객체 지향 프로그래밍을 더 직관적으로 사용할 수 있도록 제공된 기능. 내부적으로는 여전히 프로토타입 기반으로 동작함.
1. 클래스 기본 구조
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name}이(가) 소리를 냅니다.`);
}
}
const dog = new Animal("강아지");
dog.speak(); // "강아지이(가) 소리를 냅니다."
• class 키워드를 사용해 클래스를 선언할 수 있음.
• constructor는 인스턴스를 생성할 때 호출되는 특별한 메서드.
• 클래스 내부에서 메서드를 정의하면 자동으로 prototype에 추가됨.
2. 클래스 상속 (Inheritance)
ES6의 extends 키워드를 사용하면 클래스를 상속할 수 있다.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name}이(가) 소리를 냅니다.`);
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // 부모 클래스의 생성자 호출
this.breed = breed;
}
speak() {
console.log(`${this.name} (${this.breed})이(가) 멍멍!`);
}
}
const myDog = new Dog("바둑이", "진돗개");
myDog.speak(); // "바둑이 (진돗개)이(가) 멍멍!"
• extends 키워드를 사용해 Animal 클래스를 확장.
• super(name);을 사용해 부모 클래스의 constructor를 호출.
• speak 메서드를 오버라이딩(재정의)하여 동작을 변경.
3. 정적 메서드 (Static Methods)
정적 메서드는 클래스의 인스턴스가 아닌 클래스 자체에서 호출할 수 있는 메서드.
class MathUtil {
static add(a, b) {
return a + b;
}
}
console.log(MathUtil.add(2, 3)); // 5
• static 키워드를 붙이면 정적 메서드가 됨.
• 인스턴스를 생성하지 않고 클래스명.메서드명()으로 호출 가능.
4. Getter & Setter
클래스에서 getter와 setter를 사용하면 프로퍼티 값을 다룰 때 좀 더 유연하게 관리할 수 있다.
class Person {
constructor(name, age) {
this.name = name;
this._age = age; // 내부 변수 (_로 시작하는 것은 관례적인 표현)
}
get age() {
return this._age;
}
set age(value) {
if (value < 0) {
console.log("나이는 0 이상이어야 합니다.");
} else {
this._age = value;
}
}
}
const person = new Person("철수", 25);
console.log(person.age); // 25
person.age = -5; // "나이는 0 이상이어야 합니다."
console.log(person.age); // 25 (변경되지 않음)
• get age()는 person.age처럼 호출할 때 자동으로 실행됨.
• set age(value)를 사용하면 값을 설정할 때 검증 로직을 추가할 수 있음.
5. Private 필드 (#)
ES2020부터 클래스 내부에서만 접근 가능한 프라이빗 필드를 만들 수 있다.
class BankAccount {
#balance = 0; // private 변수 선언
deposit(amount) {
this.#balance += amount;
console.log(`입금 완료! 현재 잔액: ${this.#balance}원`);
}
getBalance() {
return this.#balance;
}
}
const account = new BankAccount();
account.deposit(1000);
console.log(account.getBalance()); // 1000
console.log(account.#balance); // 오류 발생 (접근 불가능)
• #balance는 클래스 내부에서만 접근 가능.
• 외부에서 직접 접근하면 오류 발생.
• 보안이 중요한 데이터를 다룰 때 유용.
정리
기능설명
class | 클래스를 정의하는 키워드 |
constructor | 인스턴스 생성 시 호출되는 메서드 |
extends | 상속을 위해 사용 |
super() | 부모 클래스의 생성자를 호출 |
static | 클래스 자체에서 호출 가능한 정적 메서드 |
get / set | 프로퍼티 값을 안전하게 가져오거나 설정하는 메서드 |
#private | 클래스 내부에서만 접근 가능한 필드 |