[Javascript] Arrow Function과 this

Nowod_K·2022년 5월 31일
0

'모던 자바스크립트 핵심가이드' 서적 발췌

Arrow Function과 this 키워드

화살표 함수 내부에서 this를 사용할 때에는 일반함수와 다르게 동작하기에 주의를 해야한다.

일반 함수에서 this 키워드는 현재 해당 함수가 바라보고 있는 객체를 바라본다.

const box = document.querySelector(".box");

box.addEventListener("click", function() {
  // 여기서 this는 현재 box라는 객체를 가르키고 있다.
  this.classList.toggle("opening");
}

하지만 화살표 함수는 this 키워드를 상위 스코프에서 상속받는다.

const box = document.querySelector(".box");

box.addEventListener("click", () => {
  // 여기서 this는 상위 스코프인 window 객체를 가르킨다.
  this.classList.toggle("opening");
}

이런 성질을 이용해 화살표 함수를 적재적소에 활용할 수 있다.

this의 잘못된 사용으로 에러가 나는 예제

const box = document.querySelector(".box");

box.addEventListener("click", function() {
  // 여기서 this는 현재 box라는 객체를 가르키고 있다.
  this.classList.toggle("opening");
  
  setTimeout(function() {
    // 일반 함수는 setTimeout의 객체인 window객체를 가르키고 있어 에러가 발생한다.
    this.classList.toggle("opening");
  }, 500)
}

Arrow Function을 활용하여 적재적소 사용

const box = document.querySelector(".box");

box.addEventListener("click", function() {
  // 여기서 this는 현재 box라는 객체를 가르키고 있다.
  this.classList.toggle("opening");
  
  setTimeout(() => {
    // 화살표 함수는 상위 scope에서 this를 상속받기에 box 객체를 가르킨다.
    this.classList.toggle("opening");
  }, 500)
}
profile
개발을 좋아하는 마음과 다양한 경험을 토대로 좋은 개발자가 되고자 노력합니다.

0개의 댓글