LoginSignup
0
1

More than 3 years have passed since last update.

Classの基本

Last updated at Posted at 2020-08-26

プロパティの定義

constructorの中にプロパティを記載するルール

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

このクラスをインスタンス化すると


const dog = new aaaa('', 2, 'チワワ');

console.log(dog);
// 出力結果
// {
//   name: '犬',
//   age: 8,
//   type: 'チワワ'
// 

メソッドの定義

基本的にはclass内においてメソッド名() { }と記載する

class Animal {
  constructor(name) {
    this.name = name;
  }

  getName() {
    return this.name;
  }
}

継承

クラスを継承するには、extends を使う


class xxxx extends 継承するclass{}

Superの使い方

継承元のクラスのプロパティに上書きせずアクセスできる

class Hero extends Character {
   //constructor(exp)としてしまうと継承元を上書きして(name, hp)が消えてエラーになる。
   //なので下記の様にSuperを使う

   constructor(name, hp, exp) {

      // 継承元のプロパティにアクセス(名前・HPの値をセット)
      super(name, hp);
      //プロパティにexp(経験値)を追加したい場合
      this.exp = exp;
  }
}

演習

動物クラス(Animal)を継承し、新しく猫(Cat)クラスを作ってください。
ただし、猫(Cat)クラスにはtypeプロパティを追加して、値にはシャムを指定します。
そして、インスタンスを作ってその中身をコンソールログに出力してください。


<script>

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

  class Cat extends Animal{
    constructor(name, age, type){
    super(name, age);
    this.type = type;
    }
  }
  const cat = new Cat('太郎', 10, 'シャム');
  console.log(cat);

</script>
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1