holdanddeepdive/javascript-deep-dive

22장 this

Opened this issue · 0 comments

일반함수와 화살표 함수의 this 바인딩 차이

일반함수의 this 바인딩

  • strict mode: undefined

  • non strict mode: 전역객체
    => new 연산자 사용: 생성한 인스턴스

  • 이런 this 바인딩이 문제가 되는 경우

    • 헬퍼함수(예: 메소드안의 중첩함수 또는 콜백함수)에서 외부함수와 this가 일치하지 않는 문제
    • this를 일치시켜주는 방법
      1. 외부함수에서 this를 다른 변수에 할당하고 헬퍼함수에서 해당변수를 사용
      2. 바인딩 메서드 사용(call, bind, apply)
      3. 화살표 함수로 쓴다.

화살표 함수의 this 바인딩

  • 화살표 함수 내부의 this는 상위 스코프의 this를 가리킨다.