Javascript arrow function (=>), this 구문 오류

카테고리 IT/코딩 Javascript

무찌마, 댓글

초고 2023. 10. 19.

자바스크립트 화살표(=>) 함수를 사용할 때, 이벤트 리스너가 부착된 DOM 요소를 지정하기 위하여 this를 사용하면 오류가 발생할 수 있으므로 event.currentTarget을 사용해야 합니다.

현재 실행 중인 이벤트 리스너가 부착된 DOM 요소를 지칭할 때에는 "event.currentTarget"

 

When a code runs after an event takes place, this is known as registering an event handler. On the other hand, the event listener listens to the event and then triggers the code for handling the event.
[출처] TechTarget

 

내용은 스택오버플로우의 글을 참고하였습니다.

Javascript - arrow functions this in event handler?

 

참고 글의 내용에서 이유를 발췌하면, 

 

"Value of this inside an arrow function is determined by where the arrow function is defined, not where it is used. So from now on, keep in mind that event.currentTarget always refers to the DOM element whose EventListeners are currently being processed".

 

event.currentTarget : the element that has the event listener attached to.
event.target : the element that triggered the event.

 

블로그 관리에 필요한 전문 지식이 부족하여 코딩 상식만으로 자바스크립트를 다루다 보니까, function() {}, 일반 함수를 사용하는 것이 오류 발생 없는 구문 실행에 도움이 될 수 있습니다.

 

관련 예문입니다.

[출처] educative, "How to add an EventListener to multiple elements in JavaScript"

 

let parent = document.getElementById("parent");
parent.addEventListener('click', (e)=> {
  console.log("event happened on", e.target);
  console.log("event registerd on", e.currentTarget);
});

Arrow functions are a concise way to write functions in JavaScript. They were introduced in ES6 and have a shorter syntax than regular functions.

 

Arrow functions do not have their own 'this' value. Instead, 'this' refers to the enclosing lexical scope. This can lead to unexpected behavior when using arrow functions as methods or constructors  

 

자바스크립트 ES5에서 'this'는 함수의 부모를 참조했었습니다. ES6에서는 화살표 함수에 어휘의 범위 지정(lexical scoping)이 적용되고, let 및 const와 같은 변수 키워드가 블록 범위 정의에 사용됩니다. ES6에서 'this'는 현재 주변 범위에 한정됩니다. 지역 영역 안에 선언된 내부 함수(inner function)는 객체의 메서드나 객체 자체가 아닌 내부 함수에만 바인딩됩니다.

 

※ 인터넷 자료를 참고하여 글을 작성하다 보니까 점점 내용이 산으로 가는 와중에 정말 쉽게 설명해 준 페이지를 발견하여 도움이 되는 단락을 발췌하였습니다.


"화살표 함수에는 this라는 변수 자체가 존재하지 않기 때문에 그 상위 환경에서의 this를 참조하게 됩니다."

[출처] Dog Foot Ruler "[JavaScript] 화살표 함수와 this 바인딩


"이벤트 수신기 내부의 this 값
비슷한 요소 다수의 이벤트를 모두 처리할 수 있는 범용 수신기를 정의하는 경우, 부착된 요소의 참조를 가져와야 하는 상황이 종종 발생합니다.

addEventListener()를 사용해 요소에 수신기를 부착하게 되면 수신기 내부의 this 값은 대상 요소를 가리키게 되며, 이는 수신기가 매개변수로 받게 되는 이벤트 객체의 currentTarget 속성과 같습니다."

[출처] mdn web docs, "EventTarget.addEventListener()}"

댓글