メインコンテンツへスキップ

JavaScript 基本part10

    継承とは

    「継承」とは、すでにあるクラスをもとに新しくクラスを作成する方法のことです。継承は、あるクラスが別のクラスの特性を引き継ぐことができるオブジェクト指向プログラミングの概念です。

    JavaScriptのクラスと継承の基本

    • クラスの定義方法

    class Animal {
      constructor(name) {
        this.name = name;
      }
    
      speak() {
        console.log(`${this.name} makes a sound.`);
      }
    }
    
    • 継承を使ってDogクラスを作成

    class Dog extends Animal {
      constructor(name, breed) {
        super(name);  // 親クラス(Animal)のコンストラクタを呼び出す
        this.breed = breed;
      }
    
      speak() {
        console.log(`${this.name} barks.`);
      }
    }
    
    const myDog = new Dog('Rex', 'Golden Retriever');
    myDog.speak();  // Rex barks.
    

    extendsキーワードで親クラスを指定し、super()を使って親クラスのコンストラクタを呼び出します

    super()とthisの使い方

    • super()は親クラスのメソッドやコンストラクタを呼び出すために使います。

    • thisはサブクラス内で使われ、インスタンスのプロパティにアクセスします。

    class Animal {
      constructor(name) {
        this.name = name;
      }
      speak() {
        console.log(`${this.name} makes a sound.`);
      }
    }
    
    class Dog extends Animal {
      constructor(name, breed) {
        super(name);  // 親クラスのコンストラクタを呼び出し
        this.breed = breed;
      }
    
      speak() {
        console.log(`${this.name}, a ${this.breed}, barks.`);
      }
    }
    
    const dog = new Dog('Buddy', 'Labrador');
    dog.speak();  // Buddy, a Labrador, barks.
    

    メソッドのオーバーライド

    サブクラスで親クラスのメソッドを再定義する方法(メソッドオーバーライド)。

    class Animal {
      speak() {
        console.log("Animal speaks");
      }
    }
    
    class Dog extends Animal {
      speak() {
        console.log("Dog barks");
      }
    }
    
    const dog = new Dog();
    dog.speak();  // Dog barks
    

    superを使ったメソッドの呼び出し

    親クラスのメソッドをサブクラスから呼び出す方法

    class Animal {
      speak() {
        console.log("Animal speaks");
      }
    }
    
    class Dog extends Animal {
      speak() {
        super.speak();  // 親クラスのメソッドを呼び出し
        console.log("Dog barks");
      }
    }
    
    const dog = new Dog();
    dog.speak();  
    // Animal speaks
    // Dog barks
    

    クラス継承の応用例

    継承の利点を活かしたコード例(例:車のクラス)

    class Vehicle {
      constructor(make, model) {
        this.make = make;
        this.model = model;
      }
    
      start() {
        console.log(`${this.make} ${this.model} is starting.`);
      }
    }
    
    class Car extends Vehicle {
      constructor(make, model, type) {
        super(make, model);
        this.type = type;
      }
    
      start() {
        super.start();
        console.log(`The car is a ${this.type}.`);
      }
    }
    
    const myCar = new Car('Toyota', 'Corolla', 'Sedan');
    myCar.start();
    // Toyota Corolla is starting.
    // The car is a Sedan.
    

    まとめ

    • クラス継承の基本的な使い方と、super()とthisの重要性

    • コードの再利用や拡張性を高めるための有用な技法

    • JavaScriptでのクラス継承は、親クラスと子クラスの関係を簡潔に表現できる強力なツールです。

    この記事が参加している募集

    あなたへのおすすめ