Menu
Coddy logo textTech

クラスをモジュールに整理する

CoddyのJavaScriptジャーニー「オブジェクト指向プログラミング」セクションの一部 — レッスン 30/56。

プロジェクトが大きくなると、すべてのクラスを1つのファイルに置くのは煩雑になります。1つのファイルに10個のクラスがあることを想像してみてください。コードを見つけたりメンテナンスしたりするのが難しくなります。

私たちはすでに、モジュールを使用してコードを整理する方法、つまり関数や変数のエクスポートインポートについて学びました。クラスでも、論理と構文は全く同じです!関数で行ったのと同様に、あるファイルからクラスをエクスポートして別のファイルにインポートすることができます。

コードをクリーンで管理しやすく保つために、クラスをモジュールに整理する練習をしましょう。 

例えば:

仕組み:

ファイル 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

チャレンジ

あなたは、モジュールごとに整理された家電量販店のシステムを持っています。Laptop クラスと Smartphone クラスは別々のファイルで作成されていますが、他のファイルから利用できるようにする必要があります。

あなたのタスク:

  1. クラスをエクスポートする(デフォルトではなく、名前付きエクスポートを使用してください):
    • 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腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

オブジェクト指向プログラミングのすべてのレッスン