[ JS ] this

김문주·2025년 4월 17일

JavaScript

목록 보기
5/5
post-thumbnail

this란?

this는 자신이 속한 객체를 가리킨다.

하지만 함수 호출 방식에 따라 this가 참조하는 값은 달라진다. (동적 바인딩)

이번 글에서는 일반 함수 호출, 메서드 호출, 생성자 함수 호출, 콜백 함수 호출 네 가지 상황에서 this가 어떻게 바뀌는지 정리해보자!


1. 일반 함수 호출

일반 함수로 호출했을 때, this는 전역 객체를 가리킨다.

(브라우저에서는 window, Node.js에서는 global)


console.log(this);
// 브라우저 → window 객체 출력

function func() {
  console.log(this);
}

func();
// 일반 함수로 호출 → this는 window

2. 메서드 호출

메서드는 객체의 프로퍼티로 등록된 함수를 말한다.

메서드로 호출하면, this는 그 메서드를 소유한 객체를 가리킨다.


const cafe = {
  brand: "이디야",
  menu: "커피",
  newCafe: {
    brand: "커피",
    menu: "음료",
    print: function () {
      console.log(this);
    },
  },
};

cafe.newCafe.print();
// → { brand: '커피', menu: '음료', print: ƒ }

✅ 요점:

  • cafe.newCafe.print() 호출 시 this는 newCafe 객체를 가리킨다.

3. 메서드를 일반 함수처럼 호출한 경우

메서드를 변수에 할당하고 호출하면 어떻게 될까?


const game = {
  name: "answn",
  age: "29",
  print: function () {
    console.log(this);
  },
};

const myGame = game.print;
myGame();
// 일반 함수 호출 → this는 window

✅ 요점:

  • game.print는 객체에 묶여있지만 myGame에 할당하는 순간 연결이 끊긴다.
  • myGame()을 일반 함수처럼 호출했기 때문에 this는 전역 객체(window)를 가리킨다.

중간 요약

호출 방식this 값
일반 함수 호출전역 객체 (window, global)
메서드 호출메서드를 소유한 객체

4. 생성자 함수 호출

생성자 함수는 new 키워드와 함께 호출해서 새로운 객체를 만든다.


function Cafe(menu) {
  console.log(this); // Cafe {}
  this.menu = menu;
}

let myCafe = new Cafe("latte");
console.log(myCafe);
// → Cafe { menu: 'latte' }

✅ 요점:

  • new Cafe("latte") 호출 시, 새로운 객체가 생성되고 this는 그 객체를 가리킨다.

만약 new 없이 호출한다면?


let myCafe = Cafe("latte");
  • 일반 함수 호출로 취급된다.
  • this는 전역 객체(window)를 가리킨다.
  • menu가 window.menu로 설정된다.
  • 반환값이 없기 때문에 myCafe는 undefined가 된다.

console.log(window.menu); // "latte"
console.log(myCafe); // undefined

5. 콜백 함수 호출

콜백 함수에서는 this가 예상과 다를 수 있다.


const game = {
  name: "answn",
  age: "",
  setGame: function (age) {
    this.age = age;
  },
};

setGame은 전달받은 age를 game 객체의 age 프로퍼티에 할당하는 메서드다.

문제 상황


function getGame(age, callback) {
  callback(age);
}

getGame("29", game.setGame);

console.log(game);
// { name: 'answn', age: '', setGame: ƒ }

❌ game.age가 기대했던 "29"로 업데이트되지 않았다.

이유는?

  • getGame 안에서 callback(age)를 일반 함수 호출로 실행했다.
  • 콜백이 객체와 분리되어 this가 전역 객체(window) 를 가리키게 됐다.
  • 결과적으로 window.age = "29"가 되어버렸다.
console.log(window.age); // "29"

최종 요약

상황this 값
일반 함수 호출전역 객체 (window)
메서드 호출메서드를 소유한 객체
생성자 함수 호출새로 생성된 객체
콜백 함수 호출 (일반)전역 객체 (window)
콜백 함수 호출 (화살표 함수)원하는 객체

한 줄 정리

"함수가 어떻게 호출되었느냐"에 따라 this가 결정된다.

new 키워드, 호출 방식, 콜백 전달 방식에 주의하자.

profile
안녕하세요:)

0개의 댓글