導入
クラスは「データ(プロパティ)」と「そのデータを扱う処理(メソッド)」をひとまとめにした設計図です。設計図から作った実体をインスタンスと呼びます。
説明
class で定義します。constructor はインスタンスを作るときに呼ばれる特別なメソッドです。
class Dog {
constructor(name, age) {
this.name = name;
this.age = age;
}
bark() {
return `${this.name}: ワン!`;
}
}
const pochi = new Dog("ポチ", 3);
console.log(pochi.name); // ポチ
console.log(pochi.bark()); // ポチ: ワン!
同じクラスから、別々のデータを持つインスタンスをいくつも作れます。
flowchart TB cls["設計図 class Dog<br/>属性: name, age / メソッド: bark()"] cls -->|"new Dog(シロ, 5)"| a["インスタンス a<br/>name=シロ"] cls -->|"new Dog(クロ, 1)"| b["インスタンス b<br/>name=クロ"]
const a = new Dog("シロ", 5);
const b = new Dog("クロ", 1);
console.log(a.bark());
console.log(b.bark());
継承(extends)で、既存クラスを拡張できます。
class Puppy extends Dog {
bark() {
return `${this.name}: キャン!`;
}
}
const p = new Puppy("モカ", 0);
console.log(p.bark());
やってみよう
Dog に別のメソッドを足したり、Puppy 以外の派生クラスを作ったりしてみましょう。
演習
class Rect { constructor(w, h) { this.w = w; this.h = h; } area() { return this.w * this.h; } } を定義し、new Rect(3, 4) の面積を表示してください。
ヒント1を見る
const r = new Rect(3, 4); console.log(r.area());