[JS] JS와 Jquery의 this차이점

K00·2022년 11월 1일
0
post-thumbnail

📌 이벤트 핸들러에서 js, 그리고 Jquery의 this가 가르키고 있는 대상은 다르다.

📙 js의 이벤트 객체

https://velog.io/@a0im/Event-target

currentTarget(=this)

이벤트 리스너를 바운딩한 DOM(태그를)을 가르킨다

target

이벤트가 "발생한" 태그를 가르킨다.

currentTarget === this
currentTarget !== target
target !== this

  <div id="test">
    <button>btn1</button>
    <button>btn2</button>
    <button>btn3</button>
  </div>

  <script>
    test.addEventListener( 'click' , function (e) {
        console.log(e.target); //click btn
        console.log(e.currentTarget);//div
        console.log(this);//div
    })
  </script>

📘 jquery의 이벤트 객체

currentTargettarget 모두 바운딩한 DOM(태그를)을 가르킨다

currentTarget === this === target

jquery가 currentTargettarget이 같은 이유는 이벤트 핸들러 부여시 각각 한 요소 하나씩 이벤트를 부여하는 메커니즘 때문에 두 속성이 동일한 요소를 가르키게 되기 때문이다 .

0개의 댓글