게으른 나에게

[JavaScript] - this 용법 본문

My Study/JavaScript

[JavaScript] - this 용법

handbefore 2025. 4. 7. 18:19

this 용법

함수의 호출 방식과 정의된 위치에 따라 참조하는 객체가 달라짐

자신이 속한 객체를 가리키는 변수

 

사용 사례

전역 범위에서의 this

  • 전역 컨텍스트에서 this는 전역 객체를 가리킴
  • 브라우저 환경에서는 window 객체가 이에 해당
console.log(this === window);

 

일반 함수에서의 this

  • 함수 내부에서의 this는 호출 방식에 따라 달라짐
    • 비엄격 모드에서는 전역 객체
    • 엄격 모드에서는 undefined
function showThis() {
  console.log(this);
}
showThis(); // 비엄격 모드: window 객체, 엄격 모드: undefined

 

객체의 메서드에서의 this

  • 해당 메서드 내부의 this는 그 메서드가 속한 객체를 가리킴
const obj = {
  value: 100,
  getValue: function() {
    return this.value;
  }
};
console.log(obj.getValue());

 

객체 메서드 내부 함수에서의 this

  • 일반 함수와 동일하게 동
    • 비엄격 모드에서는 전역 객체
    • 엄격 모드에서는 undefined
const obj = {
  value: 100,
  getValue: function() {
    function innerFunction() {
      console.log(this);
    }
    innerFunction();
  }
};
obj.getValue(); // 비엄격 모드: window 객체, 엄격 모드: undefined

이러한 동작을 방지하기 위해 self 또는 that과 같은 변수를 사용하여 외부 함수의 this를 저장하고, 내부 함수에서 이를 참조하는 패턴이 흔히 사용

const obj = {
  value: 100,
  getValue: function() {
    const self = this;
    function innerFunction() {
      console.log(self.value);
    }
    innerFunction();
  }
};
obj.getValue(); // 100

 

생성자 함수에서의 this

  • 생성자 함수를 new 키워드와 함께 호출하면, this는 새로 생성된 객체를 가리킴
function Person(name) {
  this.name = name;
}
const person1 = new Person('Alice');
console.log(person1.name); // 'Alice'

 

call, apply, bind를 통한 this 설정

  • call과 apply 메서드를 사용하면 함수 호출 시 this를 특정 객체로 지정 가능
  • bind 메서드는 새로운 함수를 생성하여 this를 영구적으로 지정
function greet() {
  console.log(this.name);
}
const person = { name: 'Bob' };
greet.call(person); // 'Bob'
const boundGreet = greet.bind(person);
boundGreet(); // 'Bob'

 

화살표 함수에서의 this

  • 자신만의 this를 가지지 않고, 외부 스코프의 this를 상속
const obj = {
  value: 100,
  getValue: () => {
    console.log(this.value);
  }
};
obj.getValue(); // undefined (전역 객체에 'value' 속성이 없기 때문)

 

 

정리

호출 방식 this가 가리키는 대상
전역에서 window (브라우저 환경)
일반 함수 비엄격 모드: window / 엄격 모드: undefined
객체의 메서드 메서드가 속한 그 객체
메서드 안의 일반 함수 전역 객체 (window) 또는 undefined
생성자 함수 새로 생성된 인스턴스 객체
화살표 함수 자신이 선언된 스코프의 this
call, apply, bind 사용 명시적으로 지정한 객체