「クラスの使用(Using classes)」の内容を、初心者でも「なるほど!」と感じられるように
やさしく・イメージ中心で噛み砕いて説明していきます。
1. クラスとは?(ざっくりイメージ)
クラスとは、
「オブジェクトを作るための設計図(テンプレート)」です。
たとえるなら…
- 「クッキーの型(クラス)」から
- 「クッキー(インスタンス)」を何枚でも作れる感じ。
class Cookie {
constructor(shape) {
this.shape = shape; // クッキーの形
}
}
const star = new Cookie("★");
const heart = new Cookie("♥");
console.log(star.shape); // ★
console.log(heart.shape); // ♥
JavaScriptここで:
class Cookie { ... }…「クッキーの型」を定義しているnew Cookie("★")…「型」から実際のオブジェクト(インスタンス)を作っている
2. constructor(コンストラクター)
クラスの中で特別なメソッドが constructor() です。
これは「オブジェクトができた瞬間に実行される最初の処理」。
例:
class Person {
constructor(name, age) {
this.name = name; // this は「今作ってる人」
this.age = age;
}
}
const alice = new Person("Alice", 20);
console.log(alice.name); // "Alice"
console.log(alice.age); // 20
JavaScript🧠 ポイント:
thisは「作られているそのインスタンス自身」を指す。constructorの中でthis.〇〇に代入すると、それがその人の「持ち物」になる。
3. メソッド(インスタンスの動き)
クラスの中では「動作」も定義できます。
それが「メソッド」。
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(`こんにちは、私は${this.name}です`);
}
}
const bob = new Person("Bob");
bob.greet(); // こんにちは、私はBobです
JavaScriptメソッドを呼ぶとき:
bob.greet()のように「.(ドット)」で呼ぶ。thisは、呼び出したオブジェクト(bob)を指す。
4. フィールド(データを入れておく場所)
今までは constructor でプロパティを作っていましたが、
クラスの中で直接書くこともできます。
class Dog {
name = "ポチ"; // フィールド(プロパティ)
bark() {
console.log(`${this.name}がワン!と鳴いた`);
}
}
const d = new Dog();
d.bark(); // ポチがワン!と鳴いた
JavaScriptこれが「パブリックフィールド」です。
どこからでもアクセスできます。
5. プライベートフィールド(#付き)
外から見られたくないデータには # をつけます。
class BankAccount {
#balance = 0; // 外から見えない
deposit(amount) {
this.#balance += amount;
}
getBalance() {
return this.#balance;
}
}
const acc = new BankAccount();
acc.deposit(100);
console.log(acc.getBalance()); // 100
console.log(acc.#balance); // ❌ エラー!(外から見えない)
JavaScript💡 つまり:
#balanceはクラスの中だけで使える秘密の変数。
6. getter / setter(プロパティ風の関数)
見た目は「変数アクセス」なのに、
裏では関数が動いている便利な仕組み。
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
get area() { // 読み取り時に呼ばれる
return this.width * this.height;
}
set area(value) { // 書き込み時に呼ばれる
this.width = Math.sqrt(value);
this.height = Math.sqrt(value);
}
}
const r = new Rectangle(2, 3);
console.log(r.area); // 6 ← get が呼ばれる
r.area = 16; // set が呼ばれる
console.log(r.width); // 4
JavaScript🧠 「見た目はプロパティ、実態は関数」と覚えましょう。
7. static(クラス専用の関数)
static をつけると、
「インスタンスではなくクラスそのものに属する」メソッドになります。
class MathTool {
static add(a, b) {
return a + b;
}
}
console.log(MathTool.add(2, 3)); // 5
JavaScriptnew しなくても使える「便利ツール的な関数」です。
8. 継承(extends)
すでにあるクラスを「引き継いで」新しいクラスを作れます。
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name}が鳴いた`);
}
}
// Animal を継承
class Dog extends Animal {
speak() {
console.log(`${this.name}がワンと鳴いた`);
}
}
const dog = new Dog("ポチ");
dog.speak(); // ポチがワンと鳴いた
JavaScript🔍 ポイント:
extendsで親クラス(Animal)を引き継ぐ。- 同じメソッド名で「上書き(オーバーライド)」できる。
- 親の機能を使いたいときは
superを使う。
9. super の使い方(親クラスを呼ぶ)
class Person
├─ constructor(name)
│ └→ this.name に代入
├─ greet() ← すべてのインスタンスで共有
├─ static method ← クラス自身に属する
└─ #secret ← プライベート変数(外から見えない)
JavaScriptインスタンスを作るとこう動く:
new Person("Alice")
↓
constructor 実行
↓
this.name = "Alice"
↓
オブジェクト完成!
まとめ
| 概念 | 意味 | キーワード |
|---|---|---|
| クラス | 設計図 | class |
| インスタンス | 実体 | new |
| constructor | 作られた瞬間に動く | 初期化処理 |
| メソッド | 動き(関数) | this を使う |
| フィールド | データの入れ物 | this.〇〇 |
| プライベート | 外から見えない | #名前 |
| getter/setter | プロパティ風に操作 | get / set |
| static | クラス専用 | クラス名.メソッド() |
| 継承 | 他のクラスを引き継ぐ | extends / super |
