LoginSignup
0
0

More than 3 years have passed since last update.

Javascript 勉強メモ② クラス、メソッド、静的メソッド、継承

Posted at

昨日から今日にかけて勉強したメモ。
これを学んでできるようになったこと。

●同じ処理をしたいときにわざわざcopy&pestしなくても、まとめることができる。
→クラス作成のメリット。フォーマットみたいなもの

●同じようなクラスだけども少し処理が違う(例えば表示したい文字列に日時だけを足したいとか)ときに、同じ処理を書かなくても、クラスが作れちゃう。しかもコード少なめ。
メリット:コード量が減らせるし、その分ミスも格段に減る。エラーが出たときに見るところが少なくて済む。

●インスタンス化しなくても良いメソッド
・デメリット:引数として情報を渡すことができない。→インスタンス化しないため
・メリット:インスタンス化しなくても呼び出したいときに呼び出し可能

'use strict';

{
  //クラスは同じようなプロパティやメソッドを何度も使う場合に便利
  //フォーマットのようなもの
  class Post {
    constructor(text){
      this.text = text;
      this.likeCount =  0;
    }
      show(){
        console.log(`${this.text} - ${this.likeCount}likes`);
      }

      like(){
        this.likeCount++;
        this.show();
      }
      //static メソッドはインスタンス化しなくてもクラス名.メソッドで呼び出すことができる (ex.Post.showInfo())
      static showInfo(){
        console.log('Posts class version 1.0');
      }
    }
  class SponsorPost extends Post{ //継承はextends method
    constructor(text,sponsor){
      super(text);//親クラスのconstructorを使うにはsuper(引数);
      this.sponsor = sponsor;
    }
    show(){
      super.show();  //親クラスのメソッドはsuper.method()で呼び出し可能
    // console.log(`${this.text} - ${this.likeCount}likes`);
        console.log(`...sponsored by ${this.sponsor}`);
      }

      // like(){
      //   this.likeCount++;
      //   this.show();
      // }
      //static メソッドはインスタンス化しなくてもクラス名.メソッドで呼び出すことができる (ex.Post.showInfo())
      // static showInfo(){
      //   console.log('Posts class version 1.0');
      // }
    }
  const posts = [
      new Post('JavaSciptの勉強中...', 12),
      new Post('プログラミング難しい',20),
      new SponsorPost('現場雑用が劇的に減らせる','hanad.j')
  ];

  posts[0].like();
  posts[0].show();
  posts[1].show();
  posts[2].show();
  posts[2].like();

  Post.showInfo();
}
0
0
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
0