Js/JavaScript js - this 바인딩 관련 - 오늘의 명언 Call & Apply 바인딩 예시 코드 class Point { constructor(x) { this.x = x; } info(y, z) { console.log(`x: ${this.x}, y: ${y}, z: ${z}`); } } var point = new Point(1); point.info(2, 3); // 결과 - x: 1, y: 2, z: 3 var point2 = {x: 100}; point.info.call(point2, 200, 300); // 결과 - x: 100, y: 200, z: 300 point.info.apply(point2, [200, 300]); // 결과 - x: 100, y: 200, z: 300 설명 함수를 바인딩하여 사용 시 this가 지정해준 object로 고정된다. call은 함수를 실행할때 파라미터를 하나씩 넘긴다. apply는 배열로 넘긴다. 이벤트 리스너 바인딩 예시 코드 class TestClass { constructor() { this.variable = 'variable'; } // this = TestClass console.log(this); test() { div.addEventListener('scroll', function() { // this = scroll event console.log(this); }); div.addEventListener('scroll', (new_this) => { // this = TestClass console.log(this); // this = scroll event console.log(new_this); }); } } 설명 위와 같이 바인딩 시 이벤트 감지 콜백 함수 등 경우에 따라 변경되는 this를 적절히 지정해줄 수 있다. 반응형 공유하기 URL 복사카카오톡 공유페이스북 공유엑스 공유 게시글 관리 구독하기Aleph Kim의 IT 블로그 저작자표시 비영리 Contents Call&Apply바인딩 예시코드 설명 이벤트리스너바인딩 예시코드 설명 당신이 좋아할만한 콘텐츠 JS - fetch api cors error 2024.07.12 js - 현재 페이지 url 관련 (location 객체) 2024.02.29 js - 변수값으로 변수명 짓기 2022.10.07 js - 변수 값으로 함수 사용 2022.10.07 댓글 0 + 이전 댓글 더보기