상황에 따른 this 바인딩

규갓 God Gyu·2025년 3월 4일

면접질문

목록 보기
80/142

자바스크립트에서 this는 함수가 호출되는 방식에 따라 값이 달라짐

  1. 전역 호출
    this는 전역 객체를 참조
    브라우저 환경에선 window 객체, node.js환경에선 global객체
function globalFunc(){
	console.log(this);
}
globalFunc();
  1. 매서드 호출
    객체의 메서드로 호출된 함수에선 this가 해당 객체를 참조
const obj = {
	name: 'Alice',
    greet: function() {
    	console.log(this.name);
    }
}
obj.greet(); // 'Alice'

  1. 생성자 함수와 클래스
    새로 생성되는 객체, 즉 인스턴스를 참조
function Person(name){
	this.name = name;
}
const person = new Person('Alice');
console.log(person.name); // 'Alice'
  1. 명시적 바인딩
    call(), apply(), bind() 메서드를 사용하면 this를 명시적으로 설정할 수 있음
function greet() {
  console.log(this.name);
}
const user = { name: "Alice" };
greet.call(user); // "Alice"
  1. 화살표 함수
    상위 스코프의 this를 상속받음, 자체적인 this 가지지 않아 사용 위치에 따라 this가 결정
const obj = {
  name: "Alice",
  greet: () => console.log(this.name),
};
obj.greet(); // undefined (전역 `this`)
  1. DOM 이벤트 핸들러
    DOM요소의 이벤트 핸들러에서 this는 기본적으로 이벤트를 발생시킨 요소를 참조
    but 화살표 함수 사용시 상위 스코프의 this를 참조
button.addEventListener("click", function () {
  console.log(this); // 클릭된 button 요소
});

이 중 화살표 함수와 명시적 바인딩은 this를 제어하는 데 유용

profile
웹 개발자 되고 시포용

0개의 댓글