개발 저장소/개발 지식 저장소

[Javascript] function과 Arrow function이 가리키는 this의 차이

이거비버 2023. 1. 10. 15:25
반응형

자바스크립트는 화살표형 함수(Arrow function)를 많이 쓴다.

 

일반 function과 Arrow function이 완벽하게 동일하지는 않다.

 

일반 function은 자신이 종속된 객체를 this로 가리키고,  Arrow function은 자신이 종속된 인스턴스를 가리킨다.

 

 

 

function FoodA() {
  this.name = "콩나물";
  return {
    name: "당근",
    load: function () {
      console.log("FoodA is " + this.name);
    },
  };
}

function FoodB() {
  this.name = "콩나물";
  return {
    name: "당근",
    load: () => {
      console.log("FoodB is " + this.name);
    },
  };
}

const foodA = new FoodA();
foodA.load(); // FoodA is 당근

const foodB = new FoodB();
foodB.load(); // FoodB is 콩나물

 

일반 함수형인 foodA.load()의 this는 자신이 종속된 객체를 가리키고(return {}) 

화살표 함수형인 foodB.load()의 this는 자신이 종속된 인스턴스(new FoodB()로 생성된 foodB 인스턴스)를 가리키기 때문에 위와 같이 결과가 달라진다.

반응형
댓글수0