MDNのドキュメントからモジュールについて勉強しました。モジュールをクラス構文で定義して、エクスポートします。インポートした側では、Javaのように書けるので個人的には馴染みがあります。
ファイル構造
- index.html
- main.js
- modules/
- square.js
- circle.js
ファイルの役割
- index.html
- main.jsの読み込み
- main.js
- モジュールの読み込み
- square.js
- 長方形に関するクラス
- circle.js
- 円に関するクラス
モジュールのサンプルコード
<!-- index.html --> <!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <title>モジュールの練習4</title> <script type="module" src="./main.js"></script> </head> <body></body> </html>
/* square.js */ // 長方形に関する変数や関数の定義 class Square{ //コンストラクタ constructor(x, y, w, h){ this.name = '長方形'; this.x = x; this.y = y; this.w = w; this.h = h; } print(){ return `この${this.name}は、座標(${this.x}、${this.y})、幅${this.w}、高さ${this.h}です。`; } } // クラスをエクスポートする export { Square };
クラス構文に書き換えます。エクスポート文がすっきりします。
/* circle.js */ // 円に関する変数や関数の定義 class Circle{ //コンストラクタ constructor(x, y, r){ this.name = '円'; this.x = x; this.y = y; this.r = r; } print(){ return `この${this.name}は、座標(${this.x}、${this.y})、半径${this.r}です。`; } } // クラスをエクスポートする export { Circle };
/* main.js */ // クラスをインポートする import { Square } from './modules/square.js'; import { Circle } from './modules/circle.js'; let square = new Square(0, 0, 10, 10); console.log(square.print()); let circle = new Circle(0, 0, 10); console.log(circle.print());
インポート文がすっきりします。モジュールをクラスで定義しておくとJavaのように書けます。
実行結果
ブラウザのコンソールに以下のように表示されます。
この長方形は、座標(0、0)、幅10、高さ10です。 この円は、座標(0、0)、半径10です。