안녕하세요. 프론트엔드 개발을 하다 보면 클래스(Class)와 모듈(Module)이라는 개념을 자주 접하게 됩니다. 두 개념 모두 코드를 조직화하는 데 도움을 주지만, 각각의 용도와 시기가 다릅니다. 이번 포스트에서는 실제 예시를 통해 클래스와 모듈의 차이점을 명확히 이해해 보도록 하겠습니다!-!
🚀 클래스(Class)란 무엇인가?
클래스는 객체를 생성하기 위한 템플릿 또는 설계도입니다. 쉽게 말해, 비슷한 속성솨 메서드를 가진 여러 객체를 만들어야 할 때 사용하는 도구입니다.
class Person {
private name: string;
private age: number;
constructor (name: string, age: number) {
this.name = name;
this.age = age;
};
greet(): string {
return `안녕하세요, 저는 ${this.name}이고 ${this.age}살입니다.`;
};
haveBirthday(): void {
this.agg++;
console.log(`생일 축하합니다! 이제 ${this.age}살입니다.`);
};
};
// 클래스를 사용해서 여러 객체 생성
const person1 = new Person{"김철수", 20};
const person2 = new Person{"김영희", 34};
person1.great(); // "안녕하세요, 저는 김철수이고 20살입니다."
person2.havaBirthday(); // "생일 축하합니다! 이제 35살입니다."
🚀 클래스의 주요 특징
- 인스턴스화 가능: new 키워드로 여러 객체 생성
- 상태(속성)와 행동(메서드) 캡슐화💊
- 상속과 다형성 지원
- 재사용 가능한 객체 템플릿
🚀 언제 클래스를 사용해야 할까?
1. 동일한 구조의 여러 객체가 필요할 때
class ShoppingCartItem {
constructor(
public name: string,
public price: number,
public quantity: number = 1
) {};
getTotalPrice(): number {
return this.price * this.quantity;
};
updateQuantity(newQuantity: number): void {
this.quantity = newQuantity;
};
};
const item1 = new ShoppingCartItem("노트북", 1000000);
const item2 = new ShoppingCartItem("마우스", 3000, 2);
const item3 = new ShoppingCartItem("키보드", 8000);
2. 복잡한 상태와 행동을 관리해야 할 때
class TodoList {
private items: string[] = [];
private completed: boolean[] = [];
addItem(item: string): void {
this.item.push(item);
this.completed.push(false);
};
completeItem(index: number): void {
if (index >=0 && index < this.items.length) {
this.completed[index] = true;
};
};
getRemaining(): string[] {
return this.items.filter((_, index) => !this.completed[index]);
};
getProgress(): string {
const total = this.item.length;
const done = this.completed.filter(Boolean).length;
return `${done}/${total} 완료`;
};
};
3. 상속이 필요한 계츨 구조를 만들 때
class Animal {
constructor(protected name: string) {};
move(distance: number): void {
console.log(`${this.name}이(가) ${distance}m 이동했습니다.`)
};
};
class Dog extends Animal {
bark(): void {
console.log(`${this.name}이(가) 멍멍 짖습니다.`)
};
};
class Cat extends Animal {
meow(): void {
console.log(`${this.name}이(가) 야옹 울었습니다.`);
};
};
🗃️ 모듈(Module)이란 무엇인가?
모듈은 관련된 코드를 하나의 파일로 그룹화하고, 필요에 따라 다른 파일에서 가져다 쓸 수 있도록 하는 방식입니다.
// utils/math.ts (모듈 파일)
export const PI = 3.14139;
export function add(a: number, b: number): number {
return a + b;
};
export function multiply(a: number, b: number): number {
return a * b;;
};
export function calculateCircleArea(radius: number): number {
return PI * radius * radius;
};
// app.ts에서 모듈 사용
import { PI, add, calculateCircleArea } from './utils/math';
console.log(PI); // 3.14159
console.log(add(5, 10)); // 15
console.log(calculateCircleArea(5)); // 78.535975
🗃️ 모듈의 주요 특징
- 코드 조직화: 관련 기능을 파일 단위로 그룹화
- 네임스페이스 제공: 이름 충돌 방지
- 재사용성: import/export로 다른 파일에서 사용
- 캡슐화: 필요한 것만 import
🗃️ 언제 모듈을 사용해야할까?
1. 관련된 유틸리티 함수들을 그룹화할 때
// utils/stringUtils.ts
export function capitalize(str: string): string {
return str.charAt(0).toUpperCase() + str.slice(1);
};
export function slugify(str: string): string {
return str.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '');
};
export function truncate(str: string, maxLength: number): string {
return str.length > maxLength
? str.slice(0, maxLength - 3) + '...'
: str;
};
2. 프로젝트 수조를 조직화할 때
// types/user.ts
export interface User {
id: string;
name: string;
email: string;
role: 'admin' | 'user' | 'guest';
};
// config/index.ts
export const API_URL = process.env.REACT_APP_API_URL || 'http://localhost:3000';
export const TIMEOUT = 5000;
export const MAX_RETRIES = 3;
// services/userService.ts
import { User } from '../types/user';
import { API_URL } from '../config';
export async function fetchUser(id: string): Promise<User> {
const response = await fetch(`${API_URL}/users/${id}`);
return response.json();
};
3. 싱글톤 패턴을 구현랄 때
// store/authStore.ts
class AuthStore {
private static instance: AuthStore;
private currentUser: User | null = null;
private constructor() {} // private constructor
static getInstance(): AuthStore {
if (!AuthStore.instance) {
AuthStore.instance = new AuthStore();
}
return AuthStore.instance;
}
setUser(user: User): void {
this.currentUser = user;
}
getUser(): User | null {
return this.currentUser;
}
logout(): void {
this.currentUser = null;
}
}
// 싱글톤 인스턴스 export
export const authStore = AuthStore.getInstance();
👥 클래스와 모듈 함께 사용하기
실제 프로젝트에서는 클래스와 모듈을 함께 사용하는 경우가 많습니다.
// models/product.ts
export class Product {
constructor(
public id: string,
public name: string,
public price: number,
public inStock: boolean = true
) {}
applyDiscount(percentage: number): number {
return this.price * (1 - percentage / 100);
}
updateStock(inStock: boolean): void {
this.inStock = inStock;
}
}
// services/productService.ts
import { Product } from '../models/product';
class ProductService {
private products: Product[] = [];
async fetchProducts(): Promise<Product[]> {
// API 호출...
return this.products;
}
findById(id: string): Product | undefined {
return this.products.find(product => product.id === id);
}
addProduct(product: Product): void {
this.products.push(product);
}
}
export const productService = new ProductService();
// hooks/useProducts.ts (React 예시)
import { useState, useEffect } from 'react';
import { productService } from '../services/productService';
import { Product } from '../models/product';
export function useProducts() {
const [products, setProducts] = useState<Product[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
productService.fetchProducts()
.then(setProducts)
.finally(() => setLoading(false));
}, []);
return { products, loading };
}
👥 결론
클래스와 모듈은 각각 다른 목적으로 사용됩니다.
- 클래스: 비슷한 속성과 메서드를 가진 여러 객체를 생성할 때 사용
- 모듈: 관련된 속성과 코드를 파일 단위로 조직화하고 재사용할 때 사용
대부분의 실제 프로젝트에서는 두 가지를 함께 사용하여 코드들 더 체계적이고 유지보수하기 쉽게 만듭니다. 클래스는 모듈 안에 포함될 수 있고, 모듈은 여러 클래스를 Import할 수 있습니다.
중요한 것은 각각의 특징을 이해하고, 상황에 맞게 적절히 사용하는 것입니다. 단순한 유틸리티 함수들은 모듈로, 복잡한 상태와 행동을 가진 객체들은 클래스로 관리하면 더 깔끔한 코드를 작성할 수 있습니다.
'인턴' 카테고리의 다른 글
[ Troubleshooting🛠️ ] react-draggable 라이브러리 사용시 버튼 드래그 & 버튼 클릭 이벤트 기능 분리하기 (0) | 2025.05.14 |
---|---|
자바스크립트 JSON과 Promise 완전 정리 (1) | 2025.05.08 |
[ Troubleshooting🛠️ ] 여러개의 Atom을 하나로 통합 (0) | 2025.04.30 |
[ Troubleshooting🛠️ ] 모달 표시 문제 해결 (0) | 2025.04.29 |
[ Troubleshooting🛠️ ] 모바일 Swiper에서 absolute 요소가 깜박이는 현상 해결 (0) | 2025.04.28 |