JavaScript「クラスの使用」要点まとめ
| クラスとは | オブジェクトを作るための「設計図」。同じ形のオブジェクトを簡単に作れる。 | class Person { ... } |
| インスタンス化 | クラスから実際のオブジェクトを作る。 | const p = new Person("Alice"); |
| constructor | インスタンスが作られたときに実行される「初期化処理」。 | constructor(name) { this.name = name; } |
| this | 「そのインスタンス自身」を指す。 | this.name = "Bob"; |
| メソッド | クラスの中で定義した「動作(関数)」。全インスタンスで共有される。 | greet() { console.log(this.name); } |
| フィールド | クラス内で定義するデータの入れ物。 | age = 20; |
| プライベートフィールド | # から始まる変数。外部からアクセスできない。 | #secret = "abc"; |
| getter / setter | プロパティのように見えて、裏で関数が動く。読み書き時に処理を追加できる。 | get name() {…} set name(v) {…} |
| static | クラス全体に属するメソッド。インスタンスではなくクラス名から呼び出す。 | static sayHi() {…} → MyClass.sayHi() |
| 継承 (extends) | 既存のクラスを引き継いで新しいクラスを作る。 | class Dog extends Animal { … } |
| super | 親クラスの constructor やメソッドを呼び出す。 | super(name); |
| クラス式 | クラスを変数に代入できる。 | const MyClass = class { … }; |
| 注意点 | – クラスは「巻き上げ」されない(定義前に使えない) – new をつけないとエラーになる – 実態は「プロトタイプ継承」を分かりやすくした構文 | |
図解イメージ
class Person
├─ constructor(name)
│ └→ this.name に代入
├─ greet() ← 共有メソッド(prototype)
├─ #secret ← プライベート変数(外から見えない)
└─ static info() ← クラス専用メソッド
const p = new Person("Alice")
↓
constructor 実行 → this.name = "Alice"
↓
p.greet() ← Person.prototype.greet() を呼ぶ
JavaScript
ひとことで言うと:
クラスは「オブジェクトをまとめて作る設計図」。
constructor で初期化し、this で自分を指し、
extends で親を引き継ぎ、static でクラス専用機能を作れる。