ES2015(ES6)から導入されたクラス構文を実装してみます。
スポンサーリンク
JavaScriptではコンストラクタ関数およびプロトタイプを利用してクラスを表現していましたが、ES2015(ES6)以降では、class命令を利用してクラス構文を実装できます。
関連ページ
上記の関連ページで説明しているBookコンストラクタ関数を、クラス構文で実装してみます。
1 2 3 4 5 6 7 8 |
function Book(title,author){ this.title = title; this.author = author; } Book.prototype.getInfo = function(){ console.log( this.title + "の著者は" + this.author ); } |
↓
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class Book{ constructor(title, author){ this.title = title; this.author = author; } getInfo(){ console.log( this.title + "の著者は" + this.author ); } } let book1 = new Book("こころ","夏目漱石"); book1.getInfo(); //こころの著者は夏目漱石 |
2〜5行目
インスタンス生成時に初期化を行うコンストラクタを定義し、プロパティを設定しています。
関連ページ
7〜9行目
JavaScriptのクラス構文は、コンストラクタ関数によるオブジェクト生成と行っていることは同じで、糖衣構文です。メソッドは実際には、オブジェクトのprototypeプロパティのメソッドとして追加されています。
アクセサプロパティ
classブロックの中で、getterやsetterを利用してプロパティを定義することができます。
関連ページ
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 Book{ constructor(title, author){ this.title = title; this.author = author; } get title(){ return this._title; } set title(value){ this._title = value; } get author(){ return this._author; } set author(value){ this._author = value; } getInfo(){ console.log( this.title + "の著者は" + this.author ); } } let book1 = new Book("坊っちゃん","夏目漱石"); book1.getInfo(); //こころの著者は夏目漱石 book1.title = 'ノルウェイの森'; book1.author = '村上春樹'; book1.getInfo(); //ノルウェイの森の著者は村上春樹 |