자바스크립트에서 this는 함수가 호출되는 방식에 따라 값이 달라짐
function globalFunc(){
console.log(this);
}
globalFunc();
const obj = {
name: 'Alice',
greet: function() {
console.log(this.name);
}
}
obj.greet(); // 'Alice'
function Person(name){
this.name = name;
}
const person = new Person('Alice');
console.log(person.name); // 'Alice'
function greet() {
console.log(this.name);
}
const user = { name: "Alice" };
greet.call(user); // "Alice"
const obj = {
name: "Alice",
greet: () => console.log(this.name),
};
obj.greet(); // undefined (전역 `this`)
button.addEventListener("click", function () {
console.log(this); // 클릭된 button 요소
});
이 중 화살표 함수와 명시적 바인딩은 this를 제어하는 데 유용