[JavaScript] this 제대로 이해하기

hoonie·2020년 12월 16일
1
post-thumbnail

안녕하세요. 이번 글에는 쉬워보이지만 은근히 헷갈리는 this의 범위에 대해 알아보겠습니다.

자바스크립트에서 매우 자주 사용하는 this는 뜻이 꽤 여러가지가 있습니다.

1.this는 단순히 그냥 사용하거나 함수 안에서 쓰게 되면 window를 의미합니다.

  • window는 DOM을 포함한 스크립트 상에서 발생되는 모든 것을 보관하고 관리하는 전역객체입니다.
	//window 객체 출력
	console.log(this);
    
    //window 객체 출력
    function thisFunction() {
        console.log(this);
      }

      thisFunction();

즉, 그냥 this는 선언된 메서드를 가지고 있는 그 상위 오브젝트를 의미합니다


2. 생성자(constructor) 안에서 사용하면 그 생성자로 새로 생성되는 객체를 의미합니다.

  • 자바스크립트에서는 비슷한 객체를 여러개 사용하길 원할 경우 이렇게 생성자를 만들어서 사용합니다(생성자는, 객체를 복사해주는 기계라고 생각하시면 됩니다)

      function Constructor() {
        this.name = "shin";
      }

      var newObject = new Constructor();

      console.log(newObject);
      //

즉, 여기서의 this는 기계에 의해 새롭게 복사될 객체라고 생각하시면 되고, this.name 은 그 객체의 name 키값에 "shin"이라는 값으로 할당해주세요. 라는 의미가 됩니다.


3.이벤트리스너 내 사용되는 this는 currentTarget과 일치합니다.


    <button id="button">버튼</button>
    <script>
      document.getElementById("button").addEventListener("click", function (e) {
        console.log(e.currentTarget);
        console.log(this);
        //<button id="button">버튼</button>
      });
    </script>

즉, 이벤트를 발생시킨 요소를 의미한다고 보시면 됩니다.


응용과정

그렇다면 다음 코드로 작동시에 this는 뭐가 나올까요?

<button id="button">버튼</button>
  <script>
   
    document.getElementById("button").addEventListener("click", function () {
     var names = ["shin", "seung", "hoon"];
      names.forEach(function (name) {
        console.log(name);
        console.log(this);
      });
    });
  </script>

우선 forEach에 대해 모르시는 분이 계실까봐 말씀드리면 forEach는 해당 배열(여기선 names)의 값들을 매개변수(여기선 name)값을 받아서 순차적으로 출력해주는 것입니다. -> 그럼 shin, seung, hoon 이 console 값으로 나오겠죠?

결론을 말씀 드리자면, 여기서의 this는 window입니다.
근본 없는 콜백함수안의 this는 window 객체를 의미합니다.

만약 이런 코드면 this는 뭘까요?


      var object = {
        names: ["shin", "seung", "hoon"],
        object2: function () {
        //객체명이 object인 객체
          console.log(this);
          object.names.forEach(function () {
          //window 객체
            console.log(this);
          });
        },
      };

      object.object2();

첫번째 호출한 this는 선언된 메서드 부모 객체를 의미하고 두번째 호출한 this는 특별한 역할을 하는 함수가 아닌 일반 함수이므로 window가 호출됩니다.

참고자료

this - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

foreach - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

0개의 댓글