A special function that runs automatically to set things up when a new object is created.
constructor(コンストラクター) は、「新しく作られるオブジェクトの最初の“設定係”」のようなものです。
クラスを使ってオブジェクトを作るときに、自動的に呼び出されて、そのオブジェクトに必要な初期の値や動作を決めてくれます。
たとえば、キャラクターを作るときに「名前」や「HP(体力)」などを最初にセットしておくようなイメージです。
JavaScript
class Player {
constructor(name, hp) {
this.name = name; // 名前をセット
this.hp = hp; // 体力をセット
}
showStatus() {
console.log(`${this.name} のHPは ${this.hp} です`);
}
}
const hero = new Player("ゆき", 100);
hero.showStatus(); // ゆき のHPは 100 です
ここで constructor の中身は、新しい Player を作るときに自動で実行されます。
このように「オブジェクトを作った瞬間に、必要な初期設定をまとめて行う場所」が constructor(コンストラクター)です。