LoginSignup
7
12

More than 5 years have passed since last update.

ブラウザのJavascriptでクラス+継承+モジュールを使う(2018.05)

Last updated at Posted at 2018-05-20

主要ブラウザの進化によって、Babelのようなトランスパイラ無して、ブラウザ上のJavaScriptでもクラス+継承+モジュールが使えるようになりました。

これは、動作確認のためのサンプルコードです。

親クラス(module_animal.js)

// module_animal.js
export class Animal {
    constructor(name) {
        this._name = name;
    }
    set name(name) {
        this._name = name;
    }
    get name() {
        return this._name;
    }
    sayHello() {
        return `BARK ${this.name}`;
    }
}

子クラス(module_cat.js)

親クラスのモジュールを、ここで読み込んでいる。変数と関数も定義してみた。

// module_cat.js
import { Animal } from "./module_animal.js";

export { message };

const message = "hello world,";

export class Cat extends Animal {
    constructor(name) {
        super(name);
    }
    sayHello() {
        return `Nyaa ${this.name}`;
    }
}

export function sayGoodby() {
    return "Goodby Baby";
}

index.js(個別にインポート)

モジュールの変数・クラス・(関数)をインポート。インポート時に指定した名前で呼び出しできる。

// index.js
import { message } from "./module_cat.js";
import { Cat } from "./module_cat.js";
import { sayGoodby } from "./module_cat.js";

const el_1 = document.getElementById('box1');
const el_2 = document.getElementById('box2');

const tama = new Cat("tama");
tama.name = "タマ";
alert(tama.sayHello());

el_1.textContent = message + tama.name;
el_2.textContent = sayGoodby();

index.js(モジュールでまとめてインポート)

モジュール全体を一括してimport。モジュール名(mcat)を名前空間にして、アクセスできる。

// index.js
import * as m from "./module_cat.js";

const el_1 = document.getElementById('box1');
const el_2 = document.getElementById('box2');

const tama = new mcat.Cat("tama");
tama.name = "タマ";
alert(tama.sayHello());

el_1.textContent = mcat.message + tama.name;
el_2.textContent = mcat.sayGoodby();

HTML

scriptタグで、type="module"を指定する

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>JavaScript Class-Object example</title>
    <link rel="stylesheet" href="style.css"></link>
  </head>

  <body>
    <p id='box1'></p>
    <p id='box2'></p>
    <script type="module" src="./index.js"></script>
  </body>
</html>

感想

JSに付き物のツールチェーンが、いくつか不要になって、いやー便利。

ダウンロードするファイルがひとつにまとまっていないけど、そこはHTTP/2の多重化でお願いしたい(そうでも、ないらしい)。

参考になるページ

7
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
12