インスタンスの生成
const greetMorning = () => { this.x = 'GoodMorning!'; } let greet_ins = new greetMorning(); console.log(greet_ins.x);
まずこれでやろうとしたらgreetMorningはコンストラクタではないと怒られてしまった。(コンストラクタはアロー関数では定義できない)
//ES6以前の書き方
const Person = function(name, age) { this.name = name; this.age = age; } Person.prototype.setName = function(name) { this.name = name; }
メソッドはprototypeを用いる
//ES6以降の書き方
class Human { constructor(name, age) { this.name = name; this.age = age; } greet() { console.log(`Hello,Iam${this.name}`); } }
メソッドにprototypeを用いる必要はない
・クラスは同じ構造のオブジェクトを使い回したいときに使う
参考
cocodrips.hateblo.jp