함수의 실행 컨텍스트를 가리키는 예약어
가장 기본적인 context로 글로벌(전역) 컨텍스트다.
여기서 출력된 window는 Javascript의 최상위 객체를 가리킨다.
console.log(this); //window
this는 해당 객체를 가리킨다.
let obj = {
num: 10,
printNumber: function(){
console.log(this.num)
},
printThis: function(){
console.log(this);
}
}
obj.printNumber(); // 10
obj.printThis(); //obj 의 값
일반 함수의 this === 전역 컨텍스트
생성자 함수의 this === 함수의 내부
function showComment(){
console.log(this);
}
showComment(); // window
function Developer(){
console.log(this);
}
let dev = new Developer(); // Developer
기본적으로 HTTP 요청과 같은 비동기 처리 코드는 전역 컨텍스트를 갖는다.
function fetchData() {
axios.get('domain.com/products').then(function() {
console.log(this);
})
}
fetchData() // window