면접 질문 관련
자바스크립트의 this
NiceKHJ
2025. 6. 11. 14:41
✅ this란 ?
this는 "누가 호출했는지" 에 따라 가리키는 대상이 달라지는 키워드 이다.
다만 화살표 함수는 예외로 자기만의 this를 갖지 않고 바깥에 있는 this를 그대로 따라간다.
✅ 상황별 this
1. 전역에서의 this
console.log(this) // 브라우저 : window
2. 일반 함수에서의 this
function khj() {
console.log(this);
}
khj(); // window (strict mode에선 undefined)
3. 객체의 메서드에서의 this
const nice = {
name:'KHJ',
say() {
console.log(this.name);
}
};
nice.say(); // KHJ
4. 함수만 따로
const hj = nice.say;
hj(); // window.name -> undefined
5. 화살표 함수에서의 this
const nice = {
name: 'KHJ',
say : ()=>{
console.log(this.name);
}
};
nice.say(); // 여기서 this는 window를 가리키기 때문에 undefined 가 나온다.
6. setTimeout 안에서 this
const king = {
name:'KHJ',
say() {
setTimeout(function(){
console.log(this.name);
},1000);
}
}
user.show(); // undefined
해결 방법 : 화살표 함수 사용
setTimeout(()=>{
console.log(this.name); // KHJ
},1000);
7. function 으로 this 를 사용하는 예시
const nice = {
name:'KHJ',
say : function(){
console.log(this.name);
};
}
nice.say(); // KHJ
✳️ 일반 함수에서 this는 해당 함수를 호출한 객체를 가리킴
✅ 요약❕
호출 방식 | this가 가리키는 것 | 설명 |
전역 함수 호출 | window | 그냥 function a() 형태로 실행 this는 window |
객체 메서드 호출 | 호출한 객체 | nice.say() -> this는 nice |
화살표 함수 | 정의된 위치의 this | this는 없고 바깥 스코프 그대로 따라감 |
setTimeout (function) | window(혹은 undefined) // useStrict에 따라 다름 | 일반 함수로 실행 setTimeout이 호출하므로 this는 window |
setTimeout(화살표 함수) | 바깥 스코프의 this | this가 없으므로 바깥 this -> 보통 메서드 안이면 객체의 this 따라감 |
생성자 함수 | 새로 생성된 객체 | new Nice() 하면 this는 새로 만들어진 객체 |
이벤트 핸들러 (function) | 이벤트 발생한 DOM 요소 | DOM 요소에 직접 바인딩한 경우 this는 이벤트 발생한 요소 |
이벤트 핸들러 (화살표 함수) | 바깥 스코프의 this | this를 만들지않음 바깥 스코프 따라감 |