this는 JavaScript에서 현재 실행 중인 컨텍스트(Context)를 참조하는 키워드로, 함수가 호출되는 방식에 따라 값이 달라진다.
전역 스코프에서 this는 전역 객체를 참조한다.
windowglobalconsole.log(this) // 브라우저 : window, Node.js: {}
const player = {
name: "Stroud",
getName: function () {
return this.name;
},
};
console.log(player.getName()); // "Stroud"
객체의 메서드 내부에서 this는 해당 메서드를 호출한 객체를 참조한다.
function Player(name) {
this.name = name;
}
const stroud = new Player("Stroud");
console.log(stroud.name); // "Stroud"
생성자 함수에서 this는 새로 생성된 객체를 참조한다.
class Animal {
constructor(type) {
this.type = type;
}
getType() {
return this.type;
}
}
const cat = new Animal("Cat");
console.log(cat.getType()); // "Cat"
클래스 내부의 this는 해당 인스턴스를 참조한다.
document.querySelector("button").addEventListener("click", function () {
console.log(this); // 클릭된 버튼 요소
});
기본적으로 this는 이벤트를 바인딩한 DOM 요소를 참조한다.
document.querySelector("button").addEventListener("click", () => {
console.log(this); // 전역 객체 (window) 또는 undefined (strict mode)
});
하지만 화살표 함수를 사용하면 this는 상위 스코프를 따른다.
const obj = {
name: "Arrow",
getName: () => {
console.log(this.name);
},
};
obj.getName(); // undefined (전역 객체의 this를 참조)
화살표 함수는 자신만의 this를 가지지 않으며, 항상 상위 스코프의 this를 참조한다.
call, apply, bind는 this 값을 명시적으로 설정하기 ㅇ ㅟ해 사용하는 메서드이다.
call은 함수를 즉시 호출하면서 첫 번째 인자로 this 값을 설정하고, 나머지 인자를 개별적으로 전달한다.
function greet(greeting, punctuation) {
console.log(`${greeting}, ${this.name}${punctuation}`);
}
const person = { name: "Alice" };
greet.call(person, "Hello", "!"); // Hello, Alice!
apply는 함수를 즉시 호출하면서 첫 번째 인자로 this 값을 설정하고, 두 번째 인자로 인자를 배열로 전달한다.
function greet(greeting, punctuation) {
console.log(`${greeting}, ${this.name}${punctuation}`);
}
const person = { name: "Alice" };
greet.apply(person, ["Hi", "."]); // Hi, Alice.
bind는 함수를 호출하지 않고, this가 고정된 새로운 함수를 반환한다.
function greet(greeting, punctuation) {
console.log(`${greeting}, ${this.name}${punctuation}`);
}
const person = { name: "Alice" };
const boundGreet = greet.bind(person, "Hey");
boundGreet("?"); // Hey, Alice?