JavaScriptのクラスサンプル

JavaScript

index.html

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="main.js"></script>
    <title>RPGのキャラクタをクラス化してみる</title>
</head>
<body>
    <p>コンソールに表示しています...</p>
</body>
</html>

main.js

// main.js

// クラス定義
class Character{
    // コンストラクタ
    constructor(name, hp, mp){
        // プロパティ
        this.name = name;
        this.hp = hp;
        this.mp = mp;
    }

    // メソッド
    getName(){
        return this.name;
    }
    
    showInfo(){
        console.log(`${this.name}`);
        console.log(`HP: ${this.hp}`);
        console.log(`MP: ${this.mp}`);
    }
}

window.addEventListener("load", ()=>{
    // クラスのインスタンス化
    const char1 = new Character("レオンハルト", 100, 20);
    const char2 = new Character("カイア", 200, 0);

    // クラスのメソッドを利用
    char1.showInfo();
    console.log(char2.getName());

});

コメント