WEB/JavaScript

[JavaScript][Event] addEventListener에서의 화살표 함수 주의사항

bay07 2024. 4. 22. 17:56

▶ addEventListener에서의 화살표 함수 주의사항 

화살표 함수는 자신만의 this를 가지지 않기 때문에
자신을 포함하고 있는 함수의 this를 상속받는다

this를 사용해야하는 경우 addEventListener에서는 일반 함수로 사용하기 

 

더보기
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <button id="function">function</button>
  <button id="arrow">arrow function</button>

  <script>
    const functionButton = document.querySelector('#function')
    const arrowButton = document.querySelector('#arrow')

    functionButton.addEventListener('click', function () {
      console.log(this) // <button id="function">function</button>
    })

    arrowButton.addEventListener('click', () => {
      console.log(this) // window
    })
  </script>
</body>

</html>

▶ 출력