코딩 공부
JavaScript의 this 키워드 완벽 가이드
새혀니
2024. 12. 2. 12:44
// 1. 전역 문맥
console.log(this); // 브라우저에서는 window 객체, Node.js에서는 global 객체
// 2. 객체 메서드에서의 this
const obj = {
name: 'Se-hyun',
greet() {
console.log(`Hello, ${this.name}!`);
},
};
obj.greet(); // Hello, Se-hyun!
// 3. 함수 내부에서의 this
function regularFunction() {
console.log(this);
}
regularFunction(); // undefined (strict mode)
// 4. 화살표 함수에서의 this
const arrowFunction = () => {
console.log(this);
};
arrowFunction(); // 화살표 함수는 상위 스코프의 this를 그대로 사용
// 5. call, apply, bind
const person = { name: 'Hyeji' };
function introduce() {
console.log(`Hi, my name is ${this.name}.`);
}
introduce.call(person); // Hi, my name is Hyeji.
//this를 이해하면 JavaScript 코드의 예측 가능성이 높아짐
//this와 관련된 자주 발생하는 문제와 해결 방법에 대한 추가 학습 유도