this

오민영·2021년 7월 16일
0

Javascript

목록 보기
6/6
post-thumbnail

함수의 실행 컨텍스트를 가리키는 예약어

window

가장 기본적인 context로 글로벌(전역) 컨텍스트다.
여기서 출력된 window는 Javascript의 최상위 객체를 가리킨다.

console.log(this); //window

객체 속성 함수 안에서의 this

this는 해당 객체를 가리킨다.

let obj = {
  num: 10,
  printNumber: function(){
    console.log(this.num)
  },
  printThis: function(){
    console.log(this);
  }
}

obj.printNumber(); // 10
obj.printThis(); //obj 의 값

함수 선언문, 생성자 함수에서의 this

일반 함수의 this === 전역 컨텍스트
생성자 함수의 this === 함수의 내부

  • new 로 인스턴스를 생성하는 순간, 함수가 실행되기 때문이다.
function showComment(){
  console.log(this);
}

showComment(); // window

function Developer(){
  console.log(this);
}

let dev = new Developer(); // Developer

데이터를 받아올 때 사용하는 HTTP 요청과 같은 비동기 처리 코드에서 this

기본적으로 HTTP 요청과 같은 비동기 처리 코드는 전역 컨텍스트를 갖는다.

function fetchData() {
	axios.get('domain.com/products').then(function() {
		console.log(this);
	})
}

fetchData() // window
profile
이것저것 정리하는 공간

0개의 댓글