본문 바로가기

웹프로그래밍/부트캠프 - Codeit

[4주차] 위클리페이퍼 - 자바스크립트에서 this 키워드의 사용과 그 특성에 대해 설명해 주세요.

728x90

this 키워드란?

  • 자신이 속한 객체 또는 자신이 생성할 인스턴스를 가리키는 자기 참조 변수
  • this가 가리키는 과정을 바인딩(binding)이라고 한다.
    • 엄격모드 여부/함수의 호출 방식/this 값이 결정되는 상황에 의해 동적으로 결정되게 된다.

this를 가리키는 값이 결정되는 경우

  1. 전역 실행 컨텍스트: → 전역 실행 컨택스트 (windows 객체 혹은 undefined)
    • 비엄격모드
      console.log(this); // 브라우저에서는 window 객체 
    • 엄격모드
      console.log(this); // undefined 
  2. 함수 호출: 일반 함수에서 this → 함수 내에서의 컨텍스트에 따라 다름
    • 비엄격모드
      function regularFunction() {
      console.log(this); // window 또는 global 객체
      }
      regularFunction();
    • 엄격모드
      function strictFunction() {
      'use strict';
      console.log(this); // undefined
      }
      strictFunction();
  3. 객체 메서드 내에서의 this → 해당 메서드를 호출한 객체
    const obj = {
    name: 'JavaScript',
    getName: function() {
        console.log(this.name);
    }
    };
    obj.getName(); // 'JavaScript'
  4. 생성자 함수에서의 this : 새로 생성되는 객체
    • 비엄격모드
      function Constructor() {
      this.property = "value";
      }
      // new 없이 호출하면 전역 객체에 property 추가
      Constructor(); // window.property = "value"
    • 엄격모드
      "use strict";
      function Constructor() {
      this.property = "value"; // TypeError: Cannot set property 'property' of undefined
      }
      Constructor(); // this가 undefined이므로 에러 발생
  5. 이벤트 핸들러에서의 this : 이벤트를 받는 요소
    document.getElementById('myButton').addEventListener('click', function() {
    console.log(this); // 클릭된 버튼 요소
    });

화살표 함수에서의 this의 특성

  • 함수가 생성된 시점의 실행 컨텍스트의 this를 상속 받음
  • 예시 코드
    • regularFunction의 setTimeout 콜백 함수는 일반 함수로서 호출되어 전역 객체의 this를 가리킴
    • arrowFunction의 setTimeout 콜백 함수는 화살표 함수로 정의되어 arrowFunction의 실행 컨텍스트인 obj의 this를 상속 받음
      const obj = {
      name: 'JavaScript',
      regularFunction: function() {
          setTimeout(function() {
              console.log(this.name); // undefined (전역 객체의 name 속성)
          }, 100);
      },
      arrowFunction: function() {
          setTimeout(() => {
              console.log(this.name); // 'JavaScript'
          }, 100);
      }
      };
      obj.regularFunction();
      obj.arrowFunction();

참고자료

728x90