【JavaScript】ECMAScript2015以降のClassの定義方法
ECMAScript2015以降では、class命令を使用して、よりわかりやすくクラスを定義することができる。
クラス定義の基本形
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
class Customer { //コンストラクター constructor(id, name) { this.id = id; this.name = name; } //プロパティ get id() { return this._id } set id(value) { this._id = value; } get name() { return this._name; } set name(value) { this._name = value; } static get domain() { return 'EC'; } //メソッド printInfo() { console.log(`${this.id}, ${this.name}`); } //静的メソッド static getStaticMember() { return this.domain; } } var c = new Customer('0001', '太郎'); //publicメソッドの呼び出し c.printInfo(); //0001, 太郎 //staticメソッドの呼び出し console.log(Customer.getStaticMember()); //EC |
extend、super命令を使った継承
ECMAScipt2015では、extends、super命令を使うことで、継承を簡潔に表現することができる。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
class Customer { //コンストラクター constructor(id, name) { this.id = id; this.name = name; } //プロパティ get id() { return this._id } set id(value) { this._id = value; } get name() { return this._name; } set name(value) { this._name = value; } static get domain() { return 'EC'; } //メソッド getInfo() { return `${this.id}, ${this.name}`; } //静的メソッド static getStaticMember() { return this.domain; } } class PrimeCustomer extends Customer { constructor(id, name, rank) { super(id, name); this.rank = rank; } get rank() { return this._rank }; set rank(value) { this._rank = value; } //メソッドのオーバーライド getInfo() { return `${super.getInfo()}, ${this.rank}` } } var c = new PrimeCustomer('0001', '太郎', 'Royal'); console.log(c.getInfo()); //0001, 太郎, Royal |
タグ :
ES2015, JavaScript