extends 継承 — class B extends A {}
JavaScript の extends は「クラスの継承」を表します。
親クラス(基底クラス)の機能を子クラス(派生クラス)が引き継ぎ、さらに自分の機能を追加できます。初心者にとっては「親の設計図をコピーして、そこに新しい部品を足す」イメージを持つと理解しやすいです。
基本のコード例
class A {
constructor(x) {
this.x = x;
}
show() {
console.log("Aの値:", this.x);
}
}
class B extends A {
constructor(x, y) {
super(x); // 親クラスの constructor を呼ぶ
this.y = y;
}
showBoth() {
console.log("Aの値:", this.x, "Bの値:", this.y);
}
}
const b = new B(10, 20);
b.show(); // → "Aの値: 10" (親クラスのメソッド)
b.showBoth(); // → "Aの値: 10 Bの値: 20" (子クラスのメソッド)
JavaScriptextends→ 親クラスを継承する。super(...)→ 親のconstructorを呼び出す。- 親のメソッドも子クラスでそのまま使える。
よく使うテンプレート集
親クラスのメソッドを拡張
class Animal {
speak() {
console.log("動物が鳴いた");
}
}
class Dog extends Animal {
speak() {
super.speak(); // 親のメソッドを呼ぶ
console.log("ワンワン!");
}
}
const d = new Dog();
d.speak();
// → "動物が鳴いた"
// → "ワンワン!"
JavaScript継承して機能追加
class Shape {
area() { return 0; }
}
class Square extends Shape {
constructor(side) {
super();
this.side = side;
}
area() {
return this.side * this.side;
}
}
const s = new Square(5);
console.log(s.area()); // → 25
JavaScript例題: ユーザーと管理者クラス
class User {
constructor(name) {
this.name = name;
}
greet() {
console.log(`こんにちは ${this.name}`);
}
}
class Admin extends User {
constructor(name, role) {
super(name);
this.role = role;
}
showRole() {
console.log(`${this.name} の役割は ${this.role} です`);
}
}
const u = new User("Aki");
u.greet(); // "こんにちは Aki"
const admin = new Admin("Mika", "管理者");
admin.greet(); // 親クラスのメソッド
admin.showRole(); // 子クラスのメソッド
JavaScript- 効果:
AdminはUserの機能を継承しつつ、独自のshowRoleを持つ。
実務でのコツ
- 共通処理は親クラスにまとめる。
- 子クラスは追加や上書きで拡張。
superを忘れるとエラーになる。 子クラスのconstructorでは必ずsuper()を呼ぶ。- オーバーライド: 子クラスで同じ名前のメソッドを書くと親を上書きできる。
ありがちなハマりポイントと対策
super()を忘れる:- 子クラスの
constructorでthisを使う前に必ずsuper()を呼ぶ。
- 子クラスの
- 親のメソッドを呼びたい:
super.methodName()を使う。
- 継承しすぎて複雑になる:
- 深い継承よりも「コンポジション(部品を組み合わせる)」を検討。
練習問題(乗り物クラス)
class Vehicle {
constructor(type) {
this.type = type;
}
run() {
console.log(`${this.type} が走る!`);
}
}
class Car extends Vehicle {
constructor(name) {
super("車");
this.name = name;
}
horn() {
console.log(`${this.name} がクラクションを鳴らす!`);
}
}
const car = new Car("プリウス");
car.run(); // "車 が走る!"
car.horn(); // "プリウス がクラクションを鳴らす!"
JavaScript直感的な指針
extends= 親クラスを継承する。super()= 親の constructor やメソッドを呼ぶ。- 親の機能をそのまま使える+子で拡張できる。
- 初心者は「動物」「乗り物」「ユーザー管理」などを継承して練習すると理解しやすい。
これを覚えれば「共通処理をまとめる」「子クラスで拡張する」といったオブジェクト指向の基本が身につきます。
