LoginSignup
0
0

More than 3 years have passed since last update.

【JavaScript】クラス概念編

Last updated at Posted at 2020-07-09

今回はクラス、インスタンス、継承といった概念の復習です。(自分用の備忘録)

0.クラスとインスタンス

クラスとは雛形や設計図と例えるのが一般的です。
インスタンスはクラスを元に作られるデータのことです。

車の製造で例えるなら、
クラスは、車を製造する設計図で、
インスタンスは設計図を元にして作られた販売している車のことになります。

1.クラス作成〜出力まで(完成)

簡単なクラス、インスタンス、継承の一連を作成しました。
細かく解説入れていきます。

// ーーーーー 親クラス ーーーーー

class Book {
  constructor(title, content) {
    this.title = title;
    this.content = content;
  }

  show() {
    console.log(`本のタイトルは ${this.title}`)
    console.log(`本の感想は ${this.content}`)
  }
}

// ーーーーー 子クラス ーーーーー

class AuthorBook extends Book {
  constructor(title, content, author) {
    super(title, content);
    this.author = author
  }
  show() {
    super.show();
    console.log(`本の著者は ${this.author}`)
  }
}

// ーーーーー インスタンス ーーーーー

const books = [
  new Book("メモの魔力", "メモの重要性がわかる")
  new Book("多動力", "ノリの良さが大切")

  new AuthorBook("革命のファンファーレ", "広告戦略の鏡", "西野亮廣")
]

// ーーーーー 結果出力 ーーーーー

books[0].show();
books[1].show();
books[2].show();

2.クラスの作成


class Book {  // クラス名の頭文字は大文字
  constructor(title, content) {  // constructor()メソッドを作ってプロパティの初期値を設定
    this.title = title;  // このクラスから作られるインスタンスはthisで表現する
    this.content = content;
  }

  show() {
    console.log(`本のタイトルは ${this.title}`)
    console.log(`本の感想は ${this.content}`)
  }
}

3.インスタンスの作成


const books = [
  // new クラス名()でインスタンスを生成
  // constructor()の引数に沿って出力したい値を入力する
  new Book("メモの魔力", "メモの重要性がわかる")
  new Book("多動力", "ノリの良さが大切")
]

4.継承


class AuthorBook extends Book {  // extends 親クラス名と記述することで、子クラスで親クラスの内容を継承できます
  constructor(title, content, author) {
    super(title, content);  // super()を使用すれば、親クラスのconstructorを継承でき、親クラスのthisを併用できる
    this.author = author
  }
  show() {
    super.show();  // super.show()を使用すれば、親クラスのshowメソッドを子クラスで継承できます
    console.log(`本の著者は ${this.author}`)
  }
}

5.結果の出力

子クラスで作成したauthorの情報が入った、インスタンスも新しく生成します。


const books = [
  // new クラス名()でインスタンスを生成
  // constructor()の引数に沿って出力したい値を入力する
  new Book("メモの魔力", "メモの重要性がわかる")
  new Book("多動力", "ノリの良さが大切")

  new AuthorBook("革命のファンファーレ", "広告戦略の鏡", "西野亮廣")
]
books[0].show();
books[1].show();
books[2].show();

6.補足

静的メソッドについて

インスタンスを生成しなくても、クラスからメソッドを呼び出すことができるstaticの使い方を紹介します。


class Book {
  constructor(title, content) {
    this.title = title;
    this.content = content;
  }

  show() {
    console.log(`本のタイトルは ${this.title}`)
    console.log(`本の感想は ${this.content}`)
  }

  static showInfo() {  // メソッド名の前にstaticと記述することでインスタンスを生成しなくてもメソッドを呼び出すことができる
    console.log("OK")
  }
}

Book.showInfo();  // クラス名.メソッド名()で呼び出すことができる

-> 注意点インスタンスを作成していないので静的メソッドでthisを扱うことはできません <-

以上

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