JavaScript~クラスの基本(インスタンス、コンストラクタ、メソッド、継承)


JavaScript~クラスの基本

コピペして使ってください。
ES6を対象としています。

クラスの定義

sample.js
//クラスの定義
class Animal { 
}
//インスタンスの生成
const animal = new Animal();

コンストラクタの定義

sample.js
//クラス内にコンストラクタを定義
class Animal {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}

//引数を渡して、インスタンスを生成
const animal = new Animal("ポチ", 8);

console.log(`名前: ${animal.name}`);
console.log(`年齢: ${animal.age}`);

メソッドの定義

sample.js
class Animal {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }  
  greet() {
    console.log("こんにちは");
  }
  info(){
    console.log(`名前:${this.name}`);
    console.log(`年齢:${this.age}`);
  }  
}

const animal = new Animal("ポチ", 8);
animal.greet();
animal.info();

クラスの継承

sample.js
class Animal {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }  
  greet() {
    console.log("こんにちは");
  }
  info(){
    this.greet();
    console.log(`名前:${this.name}`);
    console.log(`年齢:${this.age}`);
  }    }
}

// Animalクラスを継承してDogクラスを定義
class Dog extends Animal {
  //独自のメソッドを追加できる
    getHumanAge() {
    return this.age*7;
  }
}

//継承元のメソッドを使用できる
const dog = new Animal("ポチ", 3);
dog.info();
//独自のメソッドを使用できる
const humanAge = dog.getHumanAge();
console.log(`人間年齢:${humanAge}`);

オーバーライド

sample.js
class Animal {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  greet() {
    console.log("こんにちは");
  }
  info() {
    this.greet();
    console.log(`名前は${this.name}です`);
    console.log(`${this.age}歳です`);
  }
}

class Dog extends Animal {
  //constructorを追加
  constructor(name, age, breed) {
    super(name, age);
    this.breed = breed;
  } 
  info() {
    this.greet();
    console.log(`名前:${this.name}`);  
    console.log(`犬種:${this.breed}`);  
    console.log(`年齢:${this.age}`);
    const humanAge = this.getHumanAge();
    console.log(`人間年齢:${humanAge}`);
  } 
  getHumanAge() {
    return this.age * 7;
  }
}

const dog = new Dog("ポチ", 8, "チワワ");
dog.info();