BNBのプログラミング勉強記録

ガチのプログラミング初心者が駆け上がっていくブログ

メモ(javascript IV)

クラス定義、コンストラクタ、引数にてクラス呼び出し

class Animal {

  constructor(name,age) {
    this.name = name;
    this.age = age;
  }
}

const animal = new Animal("モカ",8);

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

継承とオーバーライドとsuper

子クラスで定義した独自のメソッドは、親クラスから呼び出すことはできない。下記の例だと、Animalクラスのインスタンス(animal)を作成した後にanimal.getHumanAge();としてもエラーが出る

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(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("レオ", 4,"チワワ");
dog.info();