JavaScript 클래스 | ES6 Class 문법 완벽 정리
이 글의 핵심
JavaScript 클래스: ES6 Class 문법 클래스 기본·Getter와 Setter.
들어가며
클래스란?
클래스(Class)는 객체를 찍어내기 위한 설계도(템플릿)에 해당합니다. ES6(ES2015)에서 class 문법이 도입되어, 예전 생성자 함수 패턴을 더 읽기 쉽게 쓸 수 있습니다.
클래스 이전 (ES5):
// 생성자 함수
// 함수 정의 및 구현
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.greet = function() {
console.log(`안녕하세요, ${this.name}입니다.`);
};
const person = new Person("홍길동", 25);
person.greet(); // 안녕하세요, 홍길동입니다.
클래스 사용 (ES6+):
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`안녕하세요, ${this.name}입니다.`);
}
}
const person = new Person("홍길동", 25);
person.greet(); // 안녕하세요, 홍길동입니다.
실전 경험에서 배운 교훈
이 기술을 실무 프로젝트에 처음 도입했을 때, 공식 문서만으로는 알 수 없었던 많은 함정들이 있었습니다. 특히 프로덕션 환경에서 발생하는 엣지 케이스들은 로컬 개발 환경에서는 재현조차 되지 않았죠.
가장 어려웠던 점은 성능 최적화였습니다. 처음엔 “동작만 하면 되겠지”라고 생각했지만, 실제 사용자 트래픽이 몰리면서 병목 지점들이 하나씩 드러났습니다. 특히 데이터베이스 쿼리 최적화, 캐싱 전략, 에러 핸들링 구조 등은 여러 번의 장애를 겪으면서 개선해 나갔습니다.
이 글에서는 그런 시행착오를 통해 얻은 실전 노하우와, “이렇게 하면 안 된다”는 교훈들을 함께 정리했습니다. 특히 트러블슈팅 섹션은 실제 장애 대응 경험을 바탕으로 작성했으니, 비슷한 문제를 마주했을 때 참고하시면 도움이 될 것입니다.
1. 클래스 기본
클래스 정의
class Rectangle {
// 생성자: 객체 생성 시 자동 호출
constructor(width, height) {
this.width = width;
this.height = height;
}
// 메서드
getArea() {
return this.width * this.height;
}
getPerimeter() {
return 2 * (this.width + this.height);
}
// 메서드 내에서 다른 메서드 호출
describe() {
return `넓이: ${this.getArea()}, 둘레: ${this.getPerimeter()}`;
}
}
// 객체 생성
const rect = new Rectangle(10, 5);
console.log(rect.getArea()); // 50
console.log(rect.getPerimeter()); // 30
console.log(rect.describe()); // 넓이: 50, 둘레: 30
클래스 표현식
// 익명 클래스
const Person = class {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello, ${this.name}!`);
}
};
// 기명 클래스
const Person = class PersonClass {
constructor(name) {
this.name = name;
}
};
const person = new Person("홍길동");
person.greet();
2. Getter와 Setter
getter/setter 정의
class Circle {
constructor(radius) {
this._radius = radius; // private 관례 (_prefix)
}
// getter: 속성처럼 접근
get radius() {
return this._radius;
}
// setter: 속성처럼 할당
set radius(value) {
if (value < 0) {
throw new Error("반지름은 양수여야 합니다");
}
this._radius = value;
}
// 계산된 속성
get area() {
return Math.PI * this._radius ** 2;
}
get diameter() {
return this._radius * 2;
}
set diameter(value) {
this._radius = value / 2;
}
}
// 사용
const circle = new Circle(5);
console.log(circle.radius); // 5 (getter)
console.log(circle.area); // 78.53981633974483
circle.radius = 10; // setter
console.log(circle.area); // 314.1592653589793
circle.diameter = 20; // diameter setter
console.log(circle.radius); // 10
// circle.radius = -5; // Error: 반지름은 양수여야 합니다
3. 정적 메서드와 속성
static 키워드
class MathUtils {
// 정적 속성
static PI = 3.14159;
// 정적 메서드: 인스턴스 없이 호출
static add(a, b) {
return a + b;
}
static max(...numbers) {
return Math.max(...numbers);
}
// 팩토리 메서드
static createCircle(radius) {
return new Circle(radius);
}
}
// 정적 메서드 호출
console.log(MathUtils.add(10, 20)); // 30
console.log(MathUtils.max(1, 5, 3)); // 5
console.log(MathUtils.PI); // 3.14159
// 인스턴스에서는 호출 불가
// const util = new MathUtils();
// util.add(1, 2); // TypeError
실전 예제: 팩토리 패턴
class User {
constructor(name, email, role) {
this.name = name;
this.email = email;
this.role = role;
}
// 정적 팩토리 메서드
static createAdmin(name, email) {
return new User(name, email, "admin");
}
static createGuest(name) {
return new User(name, `${name}@guest.com`, "guest");
}
hasPermission(permission) {
const permissions = {
admin: ["read", "write", "delete"],
user: ["read", "write"],
guest: [read]
};
return permissions[this.role].includes(permission);
}
}
// 사용
const admin = User.createAdmin("관리자", "[email protected]");
const guest = User.createGuest("손님");
console.log(admin.hasPermission("delete")); // true
console.log(guest.hasPermission("write")); // false
4. 상속 (Inheritance)
extends 키워드
// 부모 클래스
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name}이(가) 소리를 냅니다.`);
}
move() {
console.log(`${this.name}이(가) 움직입니다.`);
}
}
// 자식 클래스
class Dog extends Animal {
constructor(name, breed) {
super(name); // 부모 생성자 호출 (필수!)
this.breed = breed;
}
// 메서드 오버라이딩
speak() {
console.log(`${this.name}: 멍멍!`);
}
// 새 메서드
fetch() {
console.log(`${this.name}이(가) 공을 가져옵니다.`);
}
}
class Cat extends Animal {
speak() {
console.log(`${this.name}: 야옹~`);
}
}
// 사용
const dog = new Dog("바둑이", "진돗개");
dog.speak(); // 바둑이: 멍멍!
dog.move(); // 바둑이이(가) 움직입니다. (상속)
dog.fetch(); // 바둑이이(가) 공을 가져옵니다.
const cat = new Cat("나비");
cat.speak(); // 나비: 야옹~
// instanceof 체크
console.log(dog instanceof Dog); // true
console.log(dog instanceof Animal); // true
console.log(dog instanceof Cat); // false
super 키워드
class Employee {
constructor(name, salary) {
this.name = name;
this.salary = salary;
}
getInfo() {
return `${this.name} - ${this.salary.toLocaleString()}원`;
}
work() {
return `${this.name}이(가) 일합니다.`;
}
}
class Manager extends Employee {
constructor(name, salary, teamSize) {
super(name, salary); // 부모 생성자 호출
this.teamSize = teamSize;
}
// 부모 메서드 확장
getInfo() {
const baseInfo = super.getInfo(); // 부모 메서드 호출
return `${baseInfo} (팀원: ${this.teamSize}명)`;
}
manageTeam() {
return `${this.name}이(가) ${this.teamSize}명을 관리합니다.`;
}
}
const manager = new Manager("김팀장", 5000000, 5);
console.log(manager.getInfo()); // 김팀장 - 5,000,000원 (팀원: 5명)
console.log(manager.work()); // 김팀장이(가) 일합니다. (상속)
console.log(manager.manageTeam()); // 김팀장이(가) 5명을 관리합니다.
5. Private 필드 (ES2022+)
# 접두사
class BankAccount {
// Private 필드
#balance;
constructor(owner, balance) {
this.owner = owner;
this.#balance = balance;
}
// Public 메서드
deposit(amount) {
if (amount > 0) {
this.#balance += amount;
return true;
}
return false;
}
withdraw(amount) {
if (amount > 0 && amount <= this.#balance) {
this.#balance -= amount;
return true;
}
return false;
}
getBalance() {
return this.#balance;
}
// Private 메서드
#log(message) {
console.log(`[${this.owner}] ${message}`);
}
}
const account = new BankAccount("홍길동", 10000);
console.log(account.owner); // 홍길동
// console.log(account.#balance); // SyntaxError: Private field
account.deposit(5000);
console.log(account.getBalance()); // 15000
6. 실전 예제
예제 1: 게임 캐릭터
class Character {
constructor(name, hp, attack) {
this.name = name;
this.hp = hp;
this.maxHp = hp;
this.attack = attack;
}
takeDamage(damage) {
this.hp = Math.max(0, this.hp - damage);
console.log(`${this.name} HP: ${this.hp}/${this.maxHp}`);
return this.hp;
}
heal(amount) {
this.hp = Math.min(this.maxHp, this.hp + amount);
console.log(`${this.name} 회복! HP: ${this.hp}/${this.maxHp}`);
}
isAlive() {
return this.hp > 0;
}
basicAttack(target) {
console.log(`${this.name}의 공격!`);
return target.takeDamage(this.attack);
}
}
class Warrior extends Character {
constructor(name, hp, attack, defense) {
super(name, hp, attack);
this.defense = defense;
}
takeDamage(damage) {
const reduced = Math.max(0, damage - this.defense);
console.log(`${this.name}이(가) 방어력 ${this.defense}로 데미지 감소!`);
return super.takeDamage(reduced);
}
shieldBash(target) {
console.log(`${this.name}의 방패 강타!`);
return target.takeDamage(this.attack * 1.5);
}
}
class Mage extends Character {
constructor(name, hp, attack, mana) {
super(name, hp, attack);
this.mana = mana;
this.maxMana = mana;
}
fireball(target) {
if (this.mana < 20) {
console.log("마나 부족!");
return 0;
}
this.mana -= 20;
console.log(`${this.name}의 파이어볼! (마나: ${this.mana}/${this.maxMana})`);
return target.takeDamage(this.attack * 2);
}
}
// 전투 시뮬레이션
const warrior = new Warrior("전사", 150, 20, 5);
const mage = new Mage("마법사", 100, 30, 50);
console.log("=== 전투 시작 ===");
mage.basicAttack(warrior);
warrior.shieldBash(mage);
mage.fireball(warrior);
console.log("\n=== 전투 결과 ===");
console.log(`${warrior.name}: ${warrior.isAlive() ? "생존" : "사망"}`);
console.log(`${mage.name}: ${mage.isAlive() ? "생존" : "사망"}`);
예제 2: 쇼핑몰
class Product {
constructor(id, name, price, stock) {
this.id = id;
this.name = name;
this.price = price;
this.stock = stock;
}
isAvailable(quantity = 1) {
return this.stock >= quantity;
}
decreaseStock(quantity) {
if (!this.isAvailable(quantity)) {
throw new Error("재고 부족");
}
this.stock -= quantity;
}
toString() {
return `${this.name} - ${this.price.toLocaleString()}원 (재고: ${this.stock})`;
}
}
class Cart {
constructor() {
this.items = [];
}
addItem(product, quantity = 1) {
if (!product.isAvailable(quantity)) {
console.log(`${product.name} 재고 부족`);
return false;
}
const existing = this.items.find(item => item.product.id === product.id);
if (existing) {
existing.quantity += quantity;
} else {
this.items.push({ product, quantity });
}
console.log(`${product.name} ${quantity}개 추가`);
return true;
}
removeItem(productId) {
this.items = this.items.filter(item => item.product.id !== productId);
}
getTotal() {
return this.items.reduce((total, item) => {
return total + item.product.price * item.quantity;
}, 0);
}
checkout() {
this.items.forEach(item => {
item.product.decreaseStock(item.quantity);
});
const total = this.getTotal();
this.items = [];
return total;
}
printCart() {
console.log("=== 장바구니 ===");
this.items.forEach(item => {
console.log(`${item.product.name} × ${item.quantity} = ${(item.product.price * item.quantity).toLocaleString()}원`);
});
console.log(`총액: ${this.getTotal().toLocaleString()}원`);
}
}
// 사용
const laptop = new Product(1, "노트북", 1200000, 5);
const mouse = new Product(2, "마우스", 30000, 10);
const cart = new Cart();
cart.addItem(laptop, 1);
cart.addItem(mouse, 2);
cart.printCart();
const total = cart.checkout();
console.log(`결제 완료: ${total.toLocaleString()}원`);
7. 자주 하는 실수와 해결법
실수 1: super() 호출 누락
// ❌ 잘못된 방법
class Child extends Parent {
constructor(name, age) {
// super() 누락!
this.age = age; // ReferenceError
}
}
// ✅ 올바른 방법
class Child extends Parent {
constructor(name, age) {
super(name); // 부모 생성자 호출 (필수!)
this.age = age;
}
}
실수 2: 화살표 함수로 메서드 정의
// ❌ 화살표 함수 (this 바인딩 문제)
class Person {
constructor(name) {
this.name = name;
}
greet = () => {
console.log(`Hello, ${this.name}!`);
}
}
// ✅ 일반 메서드
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello, ${this.name}!`);
}
}
실수 3: new 없이 호출
class Person {
constructor(name) {
this.name = name;
}
}
// ❌ new 없이 호출
// const person = Person("홍길동"); // TypeError
// ✅ new 키워드 사용
const person = new Person("홍길동");
8. 연습 문제
문제 1: 스택 클래스
class Stack {
constructor() {
this.items = [];
}
push(item) {
this.items.push(item);
}
pop() {
if (this.isEmpty()) {
throw new Error("Stack is empty");
}
return this.items.pop();
}
peek() {
if (this.isEmpty()) {
return null;
}
return this.items[this.items.length - 1];
}
isEmpty() {
return this.items.length === 0;
}
get size() {
return this.items.length;
}
}
// 테스트
const stack = new Stack();
stack.push(1);
stack.push(2);
stack.push(3);
console.log(stack.peek()); // 3
console.log(stack.pop()); // 3
console.log(stack.size); // 2
문제 2: 타이머 클래스
class Timer {
constructor() {
this.startTime = null;
this.elapsed = 0;
this.running = false;
}
start() {
if (this.running) return;
this.running = true;
this.startTime = Date.now() - this.elapsed;
}
stop() {
if (!this.running) return;
this.running = false;
this.elapsed = Date.now() - this.startTime;
}
reset() {
this.startTime = null;
this.elapsed = 0;
this.running = false;
}
getTime() {
if (this.running) {
return Date.now() - this.startTime;
}
return this.elapsed;
}
toString() {
const ms = this.getTime();
const seconds = Math.floor(ms / 1000);
const minutes = Math.floor(seconds / 60);
const remainingSeconds = seconds % 60;
return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
}
}
// 테스트
const timer = new Timer();
timer.start();
setTimeout(() => {
console.log(timer.toString()); // 0:02
timer.stop();
}, 2000);
정리
핵심 요약
- 클래스 기본:
class키워드로 정의constructor: 생성자- 메서드: 함수 정의
- getter/setter:
get: 속성처럼 접근set: 속성처럼 할당- 유효성 검사 가능
- static:
- 정적 메서드/속성
- 인스턴스 없이 호출
- 유틸리티 함수, 팩토리 메서드
- 상속:
extends: 상속super(): 부모 생성자 호출- 메서드 오버라이딩
- Private 필드 (ES2022+):
#접두사- 클래스 외부 접근 불가
베스트 프랙티스
- ✅
constructor에서 초기화 - ✅ getter/setter로 캡슐화
- ✅ 상속 시
super()호출 - ✅ 정적 메서드로 유틸리티 함수
- ✅ Private 필드로 데이터 보호
다음 단계
관련 글
- Python 클래스 | 객체지향 프로그래밍(OOP) 완벽 정리
- C++ 클래스와 객체 |
- Java 클래스와 객체 | OOP, 상속, 인터페이스
- Kotlin 클래스와 객체 | 클래스, 상속, 인터페이스
- C++ struct vs class |
심화 부록: 구현·운영 관점
이 부록은 앞선 본문에서 다룬 주제(「JavaScript 클래스 | ES6 Class 문법 완벽 정리」)를 구현·런타임·운영 관점에서 다시 압축합니다. 도메인별 세부 구현은 글마다 다르지만, 입력 검증 → 핵심 연산 → 부작용(I/O·네트워크·동시성) → 관측의 흐름으로 장애를 나누면 원인 추적이 빨라집니다.
내부 동작과 핵심 메커니즘
flowchart TD A[입력·요청·이벤트] --> B[파싱·검증·디코딩] B --> C[핵심 연산·상태 전이] C --> D[부작용: I/O·네트워크·동시성] D --> E[결과·관측·저장]
sequenceDiagram participant C as 클라이언트/호출자 participant B as 경계(런타임·게이트웨이·프로세스) participant D as 의존성(API·DB·큐·파일) C->>B: 요청/이벤트 B->>D: 조회·쓰기·RPC D-->>B: 지연·부분 실패·재시도 가능 B-->>C: 응답 또는 오류(코드·상관 ID)
- 불변 조건(Invariant): 버퍼 경계, 프로토콜 상태, 트랜잭션 격리, FD 상한 등 단계별로 문장으로 적어 두면 디버깅 비용이 줄어듭니다.
- 결정성: 순수 층과 시간·네트워크·스케줄에 의존하는 층을 분리해야 테스트와 장애 분석이 쉬워집니다.
- 경계 비용: 직렬화, 인코딩, syscall 횟수, 락 경합, 할당·GC, 캐시 미스를 의심 목록에 둡니다.
- 백프레셔: 생산자가 소비자보다 빠를 때 버퍼·큐·스트림에서 속도를 줄이는 신호를 어디에 둘지 정의합니다.
프로덕션 운영 패턴
| 영역 | 운영 관점 질문 |
|---|---|
| 관측성 | 요청 단위 상관 ID, 에러율·지연 p95/p99, 의존성 타임아웃·재시도가 대시보드에 보이는가 |
| 안전성 | 입력 검증·권한·비밀·감사 로그가 코드 경로마다 일관적인가 |
| 신뢰성 | 재시도는 멱등 연산에만 적용되는가, 서킷 브레이커·백오프·DLQ가 있는가 |
| 성능 | 캐시·배치 크기·커넥션 풀·인덱스·백프레셔가 데이터 규모에 맞는가 |
| 배포 | 롤백 룬북, 카나리/블루그린, 마이그레이션·피처 플래그가 문서화되어 있는가 |
| 용량 | 피크 트래픽·디스크·FD·스레드 풀 상한을 주기적으로 검증하는가 |
스테이징은 데이터 양·네트워크 RTT·동시성을 프로덕션에 가깝게 맞출수록 재현율이 올라갑니다.
확장 예시: 엔드투엔드 미니 시나리오
앞선 본문 주제(「JavaScript 클래스 | ES6 Class 문법 완벽 정리」)를 배포·운영 흐름에 맞춰 옮긴 체크리스트입니다. 도메인에 맞게 단계 이름만 바꿔 적용할 수 있습니다.
- 입력 계약 고정: 스키마·버전·최대 페이로드·타임아웃·에러 코드를 경계에 둔다.
- 핵심 경로 계측: 요청 ID, 단계별 지연, 외부 호출 결과 코드를 로그·메트릭·트레이스에서 한 흐름으로 본다.
- 실패 주입: 의존성 타임아웃·5xx·부분 데이터·락 대기를 스테이징에서 재현한다.
- 호환·롤백: 설정/마이그레이션/클라이언트 버전을 되돌릴 수 있는지 확인한다.
- 부하 후 검증: 피크 대비 p95/p99, 에러율, 리소스 상한, 알림 임계값을 점검한다.
handle(request):
ctx = newCorrelationId()
validated = validateSchema(request)
authorize(validated, ctx)
result = domainCore(validated)
persistOrEmit(result, idempotentKey)
recordMetrics(ctx, latency, outcome)
return result
문제 해결(Troubleshooting)
| 증상 | 가능 원인 | 조치 |
|---|---|---|
| 간헐적 실패 | 레이스, 타임아웃, 외부 의존성, DNS | 최소 재현 스크립트, 분산 트레이스·로그 상관관계, 재시도·서킷 설정 점검 |
| 성능 저하 | N+1, 동기 I/O, 락 경합, 과도한 직렬화, 캐시 미스 | 프로파일러·APM으로 핫스팟 확인 후 한 가지씩 제거 |
| 메모리 증가 | 캐시 무제한, 구독/리스너 누수, 대용량 버퍼, 커넥션 미반납 | 상한·TTL·힙/FD 스냅샷 비교 |
| 빌드·배포만 실패 | 환경 변수, 권한, 플랫폼 차이, lockfile | CI 로그와 로컬 diff, 런타임·이미지 버전 핀 |
| 설정 불일치 | 프로필·시크릿·기본값, 리전 | 스키마 검증된 설정 단일 소스와 배포 매트릭스 표준화 |
| 데이터 불일치 | 비멱등 재시도, 부분 쓰기, 캐시 무효화 누락 | 멱등 키·아웃박스·트랜잭션 경계 재검토 |
권장 순서: (1) 최소 재현 (2) 최근 변경 범위 축소 (3) 환경·의존성 차이 (4) 관측으로 가설 검증 (5) 수정 후 회귀·부하 테스트.
배포 전에는 git add → git commit → git push 후 npm run deploy 순서를 권장합니다.
자주 묻는 질문 (FAQ)
Q. 이 내용을 실무에서 언제 쓰나요?
A. JavaScript 클래스: ES6 Class 문법 완벽 정리. 클래스 기본·Getter와 Setter로 흐름을 잡고 원리·코드·실무 적용을 한글로 정리합니다. JavaScript·클래스·class 중심으로 설명합니… 실무에서는 위 본문의 예제와 선택 가이드를 참고해 적용하면 됩니다.
Q. 선행으로 읽으면 좋은 글은?
A. 각 글 하단의 이전 글 또는 관련 글 링크를 따라가면 순서대로 배울 수 있습니다. JavaScript 시리즈 목차에서 전체 흐름을 확인할 수 있습니다.
Q. 더 깊이 공부하려면?
A. cppreference와 해당 라이브러리 공식 문서를 참고하세요. 글 말미의 참고 자료 링크도 활용하면 좋습니다.
같이 보면 좋은 글 (내부 링크)
이 주제와 연결되는 다른 글입니다.
이 글에서 다루는 키워드 (관련 검색어)
JavaScript, 클래스, class, OOP, 객체지향, 상속, ES6 등으로 검색하시면 이 글이 도움이 됩니다.