새소식

Js/JavaScript

js - this 바인딩 관련

  • -
오늘의 명언
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를 적절히 지정해줄 수 있다.
반응형

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.