ヤマカサのプログラミング勉強日記

プログラミングに関する日記とどうでもよい雑記からなるブログです。

改訂新版JavaScript本格入門 ~モダンスタイルによる基礎から現場での応用まで その7

Chapter 5 大規模開発でも通用する書き方を身につける - オブジェクト指向構文 -

クラスの続きです。

set get

ゲッターとセッターメソッドを用いて、プライベート変数を作ります。

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

  get title() {
    return this._title;
  }

  get author() {
    return this._author;
  }

  set title(value) {
    this._title = value;
  }

  set author(value) {
    this._author = value;
  }

  getInfo() {
    return this.title + ' ' + this.author;
  }
}

let b = new Book('aaa', 'bbb');
console.log(b.getInfo());

静的メソッド

class Rect {
  static getArea(height, weight) {
    return height * weight;
  }
}

console.log(Rect.getArea(3, 5));

継承

extends を使ってクラスを継承することができます。

class Human {
  constructor(height, weight) {
    this.height = height;
    this.weight = weight;
  }

  getInfo() {
    return this.height + ' ' + this.weight;
  }
}

class People extends Human{
  constructor(height, weight, language) {
    super(height, weight);
    this.language = language;
  }

  getInfo() {
    return super.getInfo() + ' ' + this.language;
  }
}

let p = new People(170, 60, 'Japanese');
console.log(p.getInfo());

感想

他の言語と比べて、オブジェクト指向に関する機能が違うなあと思いました。