Menu
Coddy logo textTech

클래스를 모듈로 구성하기

Coddy JavaScript 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨 — 56개 중 30번째.

프로젝트가 커짐에 따라, 모든 클래스를 하나의 파일에 두는 것은 복잡해집니다. 한 파일에 10개의 클래스가 있다고 상상해 보세요. 코드를 찾고 유지 관리하기가 어려워집니다.

우리는 이미 모듈을 사용하여 코드를 구성하는 방법, 즉 함수와 변수를 exporting하고 importing하는 방법을 배웠습니다. classes의 경우에도 논리와 구문은 동일합니다! 함수에서 했던 것과 마찬가지로, 한 파일에서 classes를 export하고 다른 파일로 import할 수 있습니다.

코드를 깔끔하고 관리하기 쉽게 유지하기 위해 클래스를 모듈로 구성하는 연습을 해봅시다. 

예를 들어:

작동 원리:

파일 1: furniture-base.js (기본 클래스 내보내기)

export class Furniture {
 constructor(material) {
   this.material = material;
 }
 
 describe() {
   return `${this.material} furniture`;
 }
}

파일 2: chair.js (가져오기 및 확장)

import { Furniture } from './furniture-base.js';
export class Chair extends Furniture {
 constructor(material, legs) {
   super(material);
   this.legs = legs;
 }
 
 sit() {
   return "Sitting comfortably";
 }
}

파일 3: main.js (모두 함께 사용하기)

import { Chair } from './chair.js';
import { Table } from './table.js';
const myChair = new Chair("wood", 4);
const myTable = new Table("glass", "round");
console.log(myChair.describe());  // "wood furniture"
console.log(myTable.describe());  // "glass furniture"
challenge icon

챌린지

전자 제품 매장 시스템이 모듈로 구성되어 있습니다. LaptopSmartphone 클래스는 별도의 파일에 생성되어 있지만, 다른 파일에서 사용할 수 있도록 설정해야 합니다.

수행할 작업:

  1. 클래스 내보내기 (default가 아닌 named exports를 사용하세요):
    • laptop.js에서: export를 추가하여 Laptop 클래스를 사용할 수 있게 만듭니다.
    • smartphone.js에서: export를 추가하여 Smartphone 클래스를 사용할 수 있게 만듭니다.
  2. main.js에서 클래스 가져오기:
    • laptop.js로부터 Laptop 클래스를 가져옵니다.
    • smartphone.js로부터 Smartphone 클래스를 가져옵니다.

치트 시트

클래스는 함수 및 변수와 동일한 구문을 사용하여 모듈 간에 내보내고 가져올 수 있습니다.

클래스 내보내기:

export class Furniture {
  constructor(material) {
    this.material = material;
  }
  
  describe() {
    return `${this.material} furniture`;
  }
}

클래스 가져오기 및 확장하기:

import { Furniture } from './furniture-base.js';

export class Chair extends Furniture {
  constructor(material, legs) {
    super(material);
    this.legs = legs;
  }
  
  sit() {
    return "Sitting comfortably";
  }
}

여러 클래스 가져오기:

import { Chair } from './chair.js';
import { Table } from './table.js';

const myChair = new Chair("wood", 4);
const myTable = new Table("glass", "round");

직접 해보기

// TODO: laptop.js에서 Laptop 클래스를 가져오세요

// TODO: smartphone.js에서 Smartphone 클래스를 가져오세요


const myLaptop = new Laptop();
const myPhone = new Smartphone();

console.log(myLaptop.type);      // 출력: "laptop"
console.log(myPhone.type);       // 출력: "smartphone"
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

객체 지향 프로그래밍의 모든 레슨