JAVASCRIPT

this 키워드

escaper101 2020. 11. 16. 17:49

 

this 키워드(또는 변수)는 각 실행 컨택스트마다 별도로 생성되는 특별한 키워드로써 this 키워드가 사용되고 있는 함수의 주인을 가리킨다. 

 

this가 가리키는 것은 상황 별로 다음과 같이 달라진다. 

1. 기본 함수의 this: undefined

2. 화살표 함수의 this: 화살표 함수 자체의 this는 존재하지 않지만 화살표 함수의 상위 함수를 가리킴. 

3. 메서드의 this: 메서드를 포함하고 있는 객체를 가리킴.

4. 이벤트 핸들러의 this: 해당 이벤트 핸들러가 적용된 DOM을 가리킴.

 

* 주의! this는 this가 사용되고 있는 함수 자체를 가리키거나 실행 컨택스트 마다 존재하는 개별 함수의 변수가 모여있는 공간인 variable environment을 가리키지 않는다. 

 

다음 코드를 통해 위 내용을 좀 더 상세히 살펴보자. 

const isClassic = function(publicationYear) {
  // undefined
  console.log(this)
  console.log(2020 - publicationYear > 100);
}

const isClassic2 = publicationYear => {
  // window object 
  console.log(this)
  console.log(2020 - publicationYear > 100);
}

앞서 말한 것 처럼 기본 함수의 this는 undefined이다. 그렇다면 화살표 함수의 this는 어떨까? 

화살표 함수의 this는 화살표 함수를 감싸고 있는 함수를 가리킨다. 따라서, 예시 코드에서 보는 것 처럼 화살표 함수 isClassic2의 this는 모든 함수들의 상위 object인 window object를 기리킨다. 

 

const book = {
  name: 'Pride and Prejudice',
  publicationYear: 1813, 
  isClassic: function() {
    console.log(this)
    console.log(2020 - this.publicationYear > 100);
  }
}

/*
{name: 'Pride and Prejudice',
  publicationYear: 1813,
  isClassic: [Function: isClassic]}
  true
*/
book.isClassic();

메서드의 this는 어떨까? 위 코드에서 book 객체는 isClassic 메서드를 가지고 있다. 10번 줄에서 메서드 isClassic의 this가 isClassic을 포함하고 있는 객체 book을 가리키는 것을 확인할 수 있다. 따라서 isClassic 메서드 안에서 this 키워드를 통해 book 객체의 필드 publicationYear에 접근할 수 있다. 

 

const book2 = {
  name: 'Wuthering Heights',
  publicationYear: 1847, 
}

book2.isClassic = book.isClassic;

/*
{
  name: 'Wuthering Heights',
  publicationYear: 1847,
  isClassic: [Function: isClassic]
}
true
*/
book2.isClassic();

 

이번에는 book2라는 이름의 객체가 있다. 6번 줄에서 boook 객체의 isClassic을 book2 객체에 복사했다. 이 경우에 isClassic의 this는 무엇을 가리킬까? 메서드의 this는 해당 메서드를 소유하고 있는 객체를 가리키므로 book2의 isClassic 메서드는 book2 객체를 가리키는 것을 알 수 있다. 

 

 

JavaScript에서 this 키워드는 매우 중요한 개념이므로 한번 확실히 개념을 잡으놓으면 복잡한 코드를 읽고 쓰는데 장기적으로 큰 도움이 될 것이다.