0
2

More than 1 year has passed since last update.

Javascript (クラス)

Last updated at Posted at 2022-11-13

JSのクラスについて

const posts = [
    {
      text: 'JavaScriptの勉強中…',
      likeCount: 0,
    },
    {
      text: 'プログラミング楽しい!',
      likeCount: 0,
    },
  ];

  function show(post) {console.log(`${post.text} - ${post.likeCount}いいね`);
  }

  show(posts[0]);

・post.textはオブジェクトの取り出し方法。
post=posts[0]= {text: 'JavaScriptの勉強中…',likeCount: 0,}

const posts = [
    {
      text: 'JavaScriptの勉強中…',
      likeCount: 0,
      // show: function() {
      //   console.log(`${this.text} - ${this.likeCount}いいね`);
      // },
      show() {
        console.log(`${this.text} - ${this.likeCount}いいね`);
      },
    },
    {
      text: 'プログラミング楽しい!',
      likeCount: 0,
      show() {
        console.log(`${this.text} - ${this.likeCount}いいね`);
      },
    },
  ];

  // show(posts[0]);
  posts[0].show();
  posts[1].show();

・オブジェクトではプロパティの値として、関数を持たせることができる。→その関数をメソッドという。
・show: function show(post) {
console.log(${post.text} - ${post.likeCount}いいね);}
→show,post,functionを消す。
→同じプロパティにアクセスするにはthisを使う。→そうしたら、post消す
→thisは同じプロパティということは、上のtext,likecountのことである。
→呼び出す時は同じように、posts[0].show();と呼び出す。

 ーーーーーーーーーーーそしたら下のようになるーーーーーーーーーーーーーーー

  class Post {
    constructor(text) {
      this.text = text;
      this.likeCount = 0;
    }

    show() {
      console.log(`${this.text} - ${this.likeCount}いいね`);
    }
  }

  const posts = [
    new Post('JavaScriptの勉強中…'),
    new Post('プログラミング楽しい!'),
  ];

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

・constructorでリセットする。
・const postsより前はテンプレを作成しただけ。
クラス+functionの二つのセットでテンプレ作る。
・post[0]=new Post=postの中身=textに代入する。
そしてそのオブジェクトの中のshow()にアクセス。


{
  class Post {
    constructor(text) {
      this.text = text;
      this.likeCount = 0;
    }

    show() {
      console.log(`${this.text} - ${this.likeCount} likes`);
    }

    like() {
      this.likeCount++;
      this.show();
    }
  }

  const posts = [
    new Post('JavaScriptの勉強中…'),
    new Post('プログラミング楽しい!'),
  ];

  posts[0].like();

・likeも変えるときにはこうする。
・likeも本来であれば、functionがついていた。
・this.showなところに注意。

========応用=========

 class Post {
    constructor(text) {
      this.text = text;
      this.likeCount = 0;
    }

    show() {
      console.log(`${this.text} - ${this.likeCount} likes`);
    }

    like() {
      this.likeCount++;
      this.show();
    }

    // 静的メソッド
    // thisは使えない
    static showInfo() {
      console.log('Post class version 1.0');
    }
  }

  const posts = [
    new Post('JavaScriptの勉強中…'),
    new Post('プログラミング楽しい!'),
  ];

  // posts[0].like();

  Post.showInfo();

・静的メソッド使っている。
・定義せず直接やっている。
・showもlikeもshowInfoはオブジェクとの変形である。
X:100の形が変わっただけ。

0
2
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
2