クラスをモジュールに整理する
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"チャレンジ
あなたは、モジュールごとに整理された家電量販店のシステムを持っています。Laptop クラスと Smartphone クラスは別々のファイルで作成されていますが、他のファイルから利用できるようにする必要があります。
あなたのタスク:
- クラスをエクスポートする(デフォルトではなく、名前付きエクスポートを使用してください):
laptop.js内:exportを追加してLaptopクラスを利用可能にしますsmartphone.js内:exportを追加してSmartphoneクラスを利用可能にします
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"このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
オブジェクト指向プログラミングのすべてのレッスン
8OOPコードの整理
クラスをモジュールに整理する