改訂新版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());
本
改訂新版JavaScript本格入門 ?モダンスタイルによる基礎から現場での応用まで
- 作者: 山田祥寛
- 出版社/メーカー: 技術評論社
- 発売日: 2016/09/30
- メディア: Kindle版
- この商品を含むブログを見る
感想
他の言語と比べて、オブジェクト指向に関する機能が違うなあと思いました。