なにもわからない

わかるようにしたいブログ

インスタンスの生成

  • 関数……繰り返し利用する処理をまとめたもの
  • コンストラクタ……インスタンスを作成するための関数
  • メソッド……コンストラクタ内の関数
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