본문 바로가기
TECH

this 👆🏻

by Stella-Park 2025. 7. 11.
728x90

JavaScript에서 this는 함수나 객체의 문맥(context)을 나타내는 특별한 키워드인데

코드가 실행되는 상황에 따라 this가 가리키는 대상은 달라진다.

쉽게 말해, 누가 이 코드를 호출했는가에 따라 this가 달라지는 것이다.

 

상황별 this가 가리키는 대상

1️⃣ 전역 컨텍스트 (strict mode 여부에 따라 다름)

console.log(this); // 브라우저 환경에서는 window 객체

 

  • 비엄격 모드 (non-strict, 일반 브라우저): this === window
  • 엄격 모드 (strict): this === undefined

2️⃣ 객체의 메서드에서의 this

const user = {
  name: 'Stella',
  sayHello() {
    console.log(this.name); // "Stella"
  }
};

user.sayHello(); // this는 user 객체를 가리킴
  • 객체 내부의 메서드에서는 this가 해당 객체 자체를 참조

3️⃣ 함수 호출에서의 this

function showName() {
  console.log(this.name);
}

const name = "global";
showName(); // 브라우저에서는 this === window
  • 그냥 호출하면 this는 전역 객체 (window 또는 undefined in strict mode)를 가리킴.

4️⃣ 생성자 함수에서의 this

function Person(name) {
  this.name = name;
}

const p = new Person('Stella');
console.log(p.name); // "Stella"
  • new 키워드로 호출된 생성자 함수 내부에서의 this는 새로 생성된 인스턴스를 가리킵니다.

5️⃣ 화살표 함수에서의 this

const obj = {
  name: "Stella",
  sayHi: function () {
    const arrow = () => {
      console.log(this.name);
    };
    arrow();
  }
};

obj.sayHi(); // "Stella"
  • 화살표 함수는 자신만의 this를 가지지 않음
  • 대신 자신이 정의된 외부 함수나 컨텍스트의 this를 그대로 사용

6️⃣ 이벤트 핸들러에서의 this

document.querySelector('button').addEventListener('click', function () {
  console.log(this); // 클릭한 button 요소
});
  • 일반 함수로 정의하면 this는 이벤트를 발생시킨 DOM 요소
  • 화살표 함수로 정의하면 외부 컨텍스트의 this가 그대로 유지됨.

 

this를 바인딩하는 방법들

1️⃣ bind()

function greet() {
  console.log(this.name);
}

const person = { name: 'Stella' };
const bound = greet.bind(person);
bound(); // "Stella"

 

2️⃣ call() / apply()

greet.call(person);  // "Stella"
greet.apply(person); // "Stella"

 

 

정리 및 요약

상황 this 가리키는 대상
전역 (브라우저) window 객체
메서드 호출 해당 객체
일반 함수 전역 (window 또는 undefined)
생성자 함수 새로 생성된 인스턴스
화살표 함수 선언된 위치의 this 상속
이벤트 핸들러 일반 함수: DOM 요소, 화살표 함수: 외부 this

 

  • this 때문에 헷갈릴 경우, 항상 "이 함수를 누가 호출했는가"를 따져보면 대부분 해결
  • 화살표 함수는 콜백이나 내부 함수에서 유용하게 사용됩니다 (: setTimeout, forEach 내부 )

 

이상 스텔라였습니다. ✍️

 

 

 

 

 

728x90