JavaScript this 정리

코딩아재·2022년 1월 5일
0
post-thumbnail

this

자바스크립트의 경우 함수가 어떻게 호출되었는지에 따라 this에 바인딩할 객체가 동적으로 결정되나 기본은 window를 가르킨다고 생각하면 됩니다.
그러나 내부함수는 일반 함수, 메소드, 콜백함수 어디에서 선언되었든 관게없이 this는 전역객체를 바인딩합니다.
(strict 모드에서는 undefined !!)

this가 전역객체(window)가 아닌 경우

  • 객체의 메서드
  • 생성자 함수(new로 호출하지 않으면 이때도 this는 window를 가르킨다)
  • 명시적으로 this를 바꾸는 함수 메서드 (bind, call, apply)
  • 이벤트리스너나 기타 라이브러리에 의해 내부적으로 this가 바뀐다
document.body.onclick = function() {
  console.log(this); // <body>
}
  • 화살표 함수 : 상위 함수의 this를 가져온다.(예제에서는 div를 가져온다)
$('div').on('click', function() {
  console.log(this); // <div>
  const inner = () => {
    console.log('inner', this); // inner <div>
  }
  inner();
});

내부함수의 this가 전역객체를 참조하는 것을 회피하는 방법.

1. this를 that이라는 변수에 저장하기

var value = 1;

var obj = {
  value: 100,
  foo: function() {
    var that = this;  // Workaround : this === obj

    console.log("foo's this: ",  this);  // obj
    console.log("foo's this.value: ",  this.value); // 100
    function bar() {
      console.log("bar's this: ",  this); // window
      console.log("bar's this.value: ", this.value); // 1

      console.log("bar's that: ",  that); // obj
      console.log("bar's that.value: ", that.value); // 100
    }
    bar();
  }
};

obj.foo();

2. apply, call, bind 메소드를 사용하여 this를 명시적으로 바인딩

var value = 1;

var obj = {
  value: 100,
  foo: function() {
    console.log("foo's this: ",  this);  // obj
    console.log("foo's this.value: ",  this.value); // 100
    function bar(a, b) {
      console.log("bar's this: ",  this); // obj
      console.log("bar's this.value: ", this.value); // 100
      console.log("bar's arguments: ", arguments);
    }
    bar.apply(obj, [1, 2]);
    bar.call(obj, 1, 2);
    bar.bind(obj)(1, 2);
  }
};

obj.foo();

출처

profile
코딩하는 아재입니다.

0개의 댓글

관련 채용 정보