Development/Javascript
[JS] this 키워드
madebydev
2025. 7. 10. 13:28
JavaScript의 this는 함수가 호출되는 방식에 따라 다른 값을 가지는 키워드입니다.
함수의 블록스코프 내에서 선언되어야 정상적으로 동작하며, 호출 컨텍스트에 따라 참조하는 객체가 달라집니다.
📝 일반 함수의 this = window
일반 함수에서 this는 전역 객체(브라우저에서는 window)를 가리킵니다.
이는 함수가 전역 스코프에서 호출되거나 객체의 메서드가 아닌 독립적인 함수로 호출될 때 발생합니다.
function regularFunction() {
console.log(this); // window 객체
console.log(this === window); // true
}
regularFunction();
// 객체 메서드도 변수에 할당 후 호출하면 일반 함수가 됨
const obj = {
name: "객체",
method: function() {
console.log(this); // window (일반 함수로 호출됨)
}
};
const func = obj.method;
func(); // this는 window
📝 화살표 함수의 this = 상위 스코프
화살표 함수는 자신만의 this를 가지지 않고, 상위 스코프의 this를 그대로 사용합니다.
이를 렉시컬 스코프(Lexical Scope)라고 합니다.
const obj = {
name: "객체",
regularMethod: function() {
console.log(this.name); // "객체"
const arrowFunc = () => {
console.log(this.name); // "객체" (상위 스코프의 this 사용)
};
arrowFunc();
}
};
obj.regularMethod();
// 전역에서 선언된 화살표 함수
const globalArrow = () => {
console.log(this); // window (전역 스코프의 this)
};
📝 생성자 함수의 this = 자기자신
new 키워드로 호출되는 생성자 함수에서 this는 새로 생성되는 인스턴스 객체를 가리킵니다.
function Person(name, age) {
this.name = name;
this.age = age;
this.introduce = function() {
console.log(`안녕하세요, ${this.name}입니다.`);
};
}
const person1 = new Person("김철수", 25);
const person2 = new Person("이영희", 30);
person1.introduce(); // "안녕하세요, 김철수입니다."
person2.introduce(); // "안녕하세요, 이영희입니다."
console.log(person1.name); // "김철수"
console.log(person2.name); // "이영희"
📝 이벤트 리스너의 this = 타깃
이벤트 리스너 함수에서 this는 이벤트가 발생한 DOM 요소(이벤트 타깃)를 가리킵니다.
// HTML: <button id="myButton">클릭하세요</button>
const button = document.getElementById('myButton');
button.addEventListener('click', function() {
console.log(this); // button 요소
console.log(this.tagName); // "BUTTON"
this.style.backgroundColor = 'red';
});
// 화살표 함수를 사용하면 상위 스코프의 this를 사용
button.addEventListener('click', () => {
console.log(this); // window (상위 스코프의 this)
});
📝 객체(Object)의 this = 자기자신
객체의 메서드에서 this는 해당 메서드를 소유한 객체를 가리킵니다.
const calculator = {
result: 0,
add: function(num) {
this.result += num;
return this; // 메서드 체이닝을 위해 자기자신 반환
},
subtract: function(num) {
this.result -= num;
return this;
},
getResult: function() {
return this.result;
}
};
calculator.add(10).subtract(3);
console.log(calculator.getResult()); // 7
const user = {
name: "홍길동",
greet: function() {
console.log(`안녕하세요, ${this.name}입니다.`);
}
};
user.greet(); // "안녕하세요, 홍길동입니다."
📌 주의사항
- strict mode에서는 일반 함수의 this가 undefined가 됩니다.
- call(), apply(), bind() 메서드를 사용하면 this를 명시적으로 바인딩할 수 있습니다.
- 화살표 함수는 call(), apply(), bind()로도 this를 변경할 수 없습니다.
const obj1 = { name: "객체1" };
const obj2 = { name: "객체2" };
function showName() {
console.log(this.name);
}
showName.call(obj1); // "객체1"
showName.call(obj2); // "객체2"
JavaScript의 this는 호출 방식에 따라 동적으로 결정되므로, 각 상황에 맞는 동작 방식을 이해하고 적절히 활용하는 것이 중요합니다.