独習JavaScriptの学習メモ|クラスの基礎|インスタンス化の流れ

2023年9月16日

インスタンス化の流れ

  1. new演算子によりconstructorが実行
  2. User()の引数はconstructorに引数として渡る
  3. constructor実行後、thisがnew演算子の結果として返る
  4. this.プロパティ名として追加できる
  5. 以下例ではthis.usernameとしているので、返却されるインスタンスは{ username : “hoge” }
class User {
        constructor(username, password) {
            this.username = username;
            this.password = password;
        }
        login() {
            console.log(`ログイン [ ${this.username} / ${this.password} ]`);
        }
    }

    // オブジェクトの作成:独習太郎
    const taro = new User("独習太郎", "taro-pwd");
    // オブジェクトの作成:独習花子
    const hanako = new User("独習花子", "hanako-pwd");