[JS] this란?

doitdoit
3 min read

자바스크립트에서 this는 상황에 따라 값이 달라지는 특성이 있어 헷갈릴 때가 많습니다. 이번 포스팅에서는 this의 개념과 사용법을 정리하도록하겠습니다.


📌 this란?

자바스크립트에서 this는 기본적으로 실행 컨텍스트가 생성될 때, 함께 결정된다. 실행 컨텍스트는 함수를 호출할 때 생성되므로, this는 함수를 호출할 때 결정된다고 할 수 있다.

즉, "이 함수가 어떻게 호출되었는가?"가 핵심이다.


📌 this가 결정되는 방식

1) 전역 범위에서의 this

console.log(this); // 브라우저에서는 window, Node.js에서는 global을 출력
  • 브라우저 환경에서는 window 객체를 가리킨다.

  • Node.js 환경에서는 global 객체를 가리킨다.

  • use strict 모드에서는 undefined가 된다.

2) 함수로서 호출한 경우 this

function myFunction() {
  console.log(this); // 전역 객체 (브라우저에서는 window, Node.js에서는 global)
}

myFunction();
  • 일반 함수 내부에서 this를 호출하면, 기본적으로 전역 객체를 가리킨다.

2) 메서드로서 호출한 경우 this

const obj = {
  name: "JavaScript",
  showThis: function () {
    console.log(this);
  },
};
obj.showThis(); // obj 객체
  • 객체의 메서드에서 this는 해당 객체를 가리킨다

3) 화살표 함수에서 this

const obj = {
  name: "JavaScript",
  showThis: () => {
    console.log(this);
  },
};
obj.showThis(); // window (화살표 함수는 상위 스코프의 this를 사용)
  • 화살표 함수는 자신만의 this를 가지지 않고, 상위 스코프의 this를 그대로 사용

  • 위 코드에서는 obj가 아니라 window를 출력

4) 생성자 함수에서 this

function Person(name) {
  this.name = name;
}
const me = new Person("John");
console.log(me.name); // "John"
  • new 키워드를 사용하면 this새롭게 생성된 객체를 가리킨다

5) 이벤트 핸들러에서 this

document.getElementById("btn").addEventListener("click", function () {
  console.log(this); // 클릭된 요소
});
  • this는 이벤트가 발생한 요소를 가리킨다

이벤트 핸들러에서 화살표 함수 사용 시 주의

document.getElementById("btn").addEventListener("click", () => {
  console.log(this); // window (상위 스코프의 this를 사용)
});
  • 화살표 함수를 사용하면 thiswindow가 된다

📌 this를 명확하게 바인딩하는 방법

1) call, apply

callapply는 즉시 함수를 실행하면서 this를 지정할 수 있다

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

const user = { name: "Alice" };

greet.call(user); // "Alice"
greet.apply(user); // "Alice"
  • call(thisArg, arg1, arg2, ...) → 인자를 개별적으로 전달

  • apply(thisArg, [arg1, arg2, ...]) → 인자를 배열로 전달

2) bind

  • bind는 새로운 함수를 반환하며 this를 고정시킨다
const obj = { name: "Alice" };

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

const boundGreet = greet.bind(obj);
boundGreet(); // "Alice"

📌 this가 예상과 다르게 동작하는 경우

1) 클래스에서 this 문제

class Counter {
  constructor() {
    this.count = 0;
  }

  increase() {
    console.log(this);
    this.count++;
  }
}

const counter = new Counter();
const inc = counter.increase;
inc(); // undefined 또는 에러 발생 (this가 counter를 가리키지 않음)
  • increase 메서드를 변수에 할당하면 thisundefined가 됩니다.

  • 해결 방법: bind 사용

const incFixed = counter.increase.bind(counter);
incFixed(); // 정상 작동

2) setTimeout에서 this 문제

const obj = {
  name: "Alice",
  sayHi: function () {
    setTimeout(function () {
      console.log(this.name); // undefined (window를 가리킴)
    }, 1000);
  },
};

obj.sayHi();
  • 해결 방법: 화살표 함수 사용
const obj = {
  name: "Alice",
  sayHi: function () {
    setTimeout(() => {
      console.log(this.name); // "Alice"
    }, 1000);
  },
};

obj.sayHi();
  • 화살표 함수는 상위 스코프의 this를 유지하기 때문에 해결된다

📌 this 정리표

호출 방식this
전역 실행 (브라우저)window (use strict이면 undefined)
객체의 메서드해당 객체
생성자 함수생성된 인스턴스
화살표 함수상위 스코프의 this를 따름
call / apply지정한 객체
bind새로운 함수, 지정된 this 고정
이벤트 핸들러이벤트가 발생한 요소 (addEventListener에서 화살표 함수는 window)
setTimeout기본적으로 window, 화살표 함수 사용 시 상위 this 유지

결론

this는 함수가 어떻게 호출되었는지에 따라 값이 달라진다. 특히, 화살표 함수의 특성과 bind, call, apply를 활용하는 방법을 이해하면 this 관련 문제를 쉽게 해결할 수 있다! 🚀

0
Subscribe to my newsletter

Read articles from doit directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

doit
doit

프론트엔드 개발자 doit입니다.