一般関数のthis VS矢印関数のthis

3572 ワード

一般関数のthis


関数がどのように呼び出されるかによって、この関数にバインドされているオブジェクトが「動的」であることが決まります.
const car = {
  type: 'bus',
}

Object.prototype.Mycar = function() {
  console.log(`My car is ${this.name}`);
};

car.Mycar();//My car is bus.

矢印関数のthis


このオブジェクトにバインドされているオブジェクトは、[静的](Static)として決定されます.メソッドを呼び出すオブジェクトではなく、上位マシンのthisを指します.
const car = {
  type: 'bus',
}

Object.prototype.Mycar = () => console.log(`My car is ${this.name}`);
car.Mycar(); // My car is undefined