Front-end/JavaScript

[JavaScript]  this란 무엇인가

helloyukyung 2023. 1. 15. 01:55

자바스크립트의 this에 대해 알아보자.

this는 Javascript의 예약어이다.

기본적으로 this는 전역 객체를 가리킨다.

Node환경에서는 global객체를, 브라우저 환경에서는 Window객체를 가리킨다.

(브라우저 도구탭에서 this를 쳐보면 Window객체가 출력된다.)

this; // Window{}

this는 가리키는 값(this 바인딩), 함수 호출 방식에 의해 동적으로 결정된다.

(바인딩 : 식별자와 값을 연결하는 과정)

this를 알기 위해서는 “누가 나를 불렀는가”를 알면 된다.

여기서 "누가"는 콘텍스트 객체이며 this가 바라보고 있는 객체 정도로 인지하자.

const car = {
  name: 'KIA',
  getName: function () {
console.log('car getName', this)
  }
}
// 1.
car.getName()
// ===> car {name : ' KIA' , getName : f}

// 2.
const globalCar = car.getName;
globalCar()
// ===> window 객체 호출

// 3.
const car2 = {
    name : "hyundai",
    getName : car.getName,
}
car2.getName()
// ===> car2 {name : ' hyundai' , getName : f}

bind 함수

.bind함수는 this 고정시키는데 사용한다.

위 2번의 this를 car로 고정시켜보자

const bindGetName = car2.getName.bind(car);
bindGetName()
// {name : 'KIA', getName : f}

화살표 함수에서의 this

const testCar = {
  name: 'benz',
  getName: function () {
    console.log('getName', this)
    const innerFunc = function () {
      console.log('innerFunc', this)
    }
    innerFunc()
  }
}

innerFunc는 window 객체를 호출한다

innerFunc와 getName this를 같게 만들려면 어떻게 해야될까

javascript에서는 일반함수에서의 this와 화살표 함수에서의 this가 다르다.

화살표 함수에서의 this는 함수가 속해있는 곳의 상위 this를 계승받는다.

(+ 화살표함수에서는 bind를 사용할 수 없다.)

const testCar = {
  name: 'benz',
  getName: function () {
    console.log('getName', this)
    const innerFunc = ()=> {
      console.log('innerFunc', this)
    }
    innerFunc()
  }
}