0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

クラスの全てのメンバ変数・メンバ関数を設定するためには、
インスタンス名.変数名 = 変数 といった具合に直接代入するのは、正直だるいです!

「もっと楽したい」って思ったので、今回は コンストラクタ を使って楽をしよう!


問題概要

  • Employee クラスがある
  • numbername という2つのメンバ変数
  • getnum()getname() のメンバ関数で値を取り出す
  • コンストラクタという機能を用いてメンバ変数を設定

入力例:

3
make 1 nana
getnum 1
getname 1

出力例:

1
nana

https://paiza.jp/works/mondai/class_primer/class_primer__constructor






✅OKコード例:

const rl = require('readline').createInterface({input:process.stdin});
const lines = [];

rl.on ('line', (input) => {
    lines.push(input);
});


rl.on ('close', () => {
    const N = Number(lines[0]);
    
    class Employee{
        constructor(number, name){
            this.number = Number(number);
            this.name = name;
        }
        
        getnum() {
            return this.number;
        }
        
        getname() {
            return this.name;
        }
    }
    
    
    const employees = [];
    
    for (let i = 1; i <= N; i++) {
        const tokens = lines[i].split(' ');
        const command = tokens[0];
        
        if (command === 'make') {
            employees.push(new Employee(tokens[1], tokens[2]));
        }
        
        else if (command === 'getnum'){
            const index = tokens[1] - 1;
            console.log(employees[index].getnum());
        }
        
        else if (command === 'getname'){
            const index = tokens[1] - 1;
            console.log(employees[index].getname());
        }
    }
});



✅ コンストラクタとは?

クラスからインスタンス(オブジェクト)を作るときに最初に実行される特別なメソッド

主な役割は:

  • 初期化(メンバ変数に値を入れる)

  • 必要な設定をまとめて行う




✅ 今回のコードの場合

class Employee {
  constructor(number, name) {
    this.number = Number(number);
    this.name = name;
  }

  getnum() { return this.number; }
  getname() { return this.name; }
}

ここで constructor(number, name) がコンストラクタです。




✅ どう使われている?


例えばこの行:

employees.push(new Employee(tokens[1], tokens[2]));

new Employee(1, "nana") と呼ぶと

`constructor{ が自動で実行される

渡した値 1"nana"numbername に入る

だから this.numberthis.name に初期値がセットされる




✅ コンストラクタがないとどうなる?


もしコンストラクタを書かなかったら、

const e = new Employee();
e.number = 1;
e.name = "nana";

と 外からわざわざ代入 しないといけないので面倒で、ミスもしやすい。




✅ コンストラクタの特徴

  • constructor という名前で必ず書く(他の名前にはできない)
  • 1つのクラスに1つだけ
  • this を使ってメンバ変数を初期化する
  • new をつけてクラスを呼んだときだけ自動で実行される





✅ まとめ:コンストラクタの良いところ

✔️ 初期設定をまとめられるので、コードがスッキリ

✔️ インスタンス生成時の 値漏れ・設定漏れを防げる

✔️ new で作った瞬間に「完全な状態」のオブジェクトが作れる

僕の失敗談(´;ω;`)と解決法🐈






💡おまけ:コンストラクタの応用例

✅ 1. 引数なしのコンストラクタ

何も引数を受け取らないコンストラクタ。

必要な初期値を中で固定でセットする。


例:

class User {
  constructor() {
    this.name = "Guest";
    this.isAdmin = false;
  }
}

const u = new User();
console.log(u.name); // Guest

📌 ポイント

  • 値を外から渡さずに、あらかじめ決め打ちで初期化する場合に便利。
  • テスト用や一時的なオブジェクトでよく使う。




✅ 2. デフォルト値を設定するコンストラクタ

constructor の引数の = は 「デフォルト値を設定する」という意味。

引数が渡されなかった場合にだけ、代わりの初期値を入れる。


例:

class User {
  constructor(name = "Guest", isAdmin = false) {
    this.name = name;
    this.isAdmin = isAdmin;
  }
}

const u1 = new User("Alice", true);
console.log(u1.name); // Alice

const u2 = new User();
console.log(u2.name); // Guest ← デフォルト値

📌 ポイント

  • constructor(name = “Guest”) のように = を書けばOK。
  • 渡されたら引数を使い、渡されなければデフォルトが適用される。
  • オプション設定 によく使う。



constructor(name, isAdmin) {
  this.name = name || "Guest";
  this.isAdmin = isAdmin || false;
}

と 手動で書く方法 と同じ意味。




✅ 3. 継承でのコンストラクタの使い方

extends を使うと親クラスのプロパティを引き継げる。

子クラスのコンストラクタでは super() を呼ばないといけない。


例:

class Employee {
  constructor(number, name) {
    this.number = number;
    this.name = name;
  }
}

class Manager extends Employee {
  constructor(number, name, department) {
    super(number, name);  // ← 親クラスのconstructorを呼ぶ!
    this.department = department;  // 子クラス独自のプロパティ
  }
}

const m = new Manager(1, "nana", "HR");
console.log(m.number);      // 1
console.log(m.department);  // HR

📌 ポイント

  • super() は必ず 子クラスのコンストラクタの最初 に呼ぶ。
  • super() は親クラスのコンストラクタを呼び出す特別なキーワード。
  • 親の初期化 → 子の初期化 の順で処理される。
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?