JavaScript에서 this 키워드 이해하기: 궁극적인 가이드

발행: (2026년 4월 24일 AM 04:20 GMT+9)
7 분 소요
원문: Dev.to

I’m happy to translate the article for you, but I’ll need the text you’d like translated. Could you please paste the content (or the portion you want translated) here? I’ll keep the source link and all formatting exactly as you specify.

소개

파티에 있다고 상상해 보세요. 누군가가 “야, 너!” 라고 외칩니다 – 그런데 그게 누구에게 향한 걸까요? 전적으로 상대가 바라보고 있는 사람에 달려 있습니다. 이것이 바로 JavaScript의 this 키워드가 작동하는 방식입니다. this는 고정된 정체성을 갖고 있지 않으며, 함수를 호출한 사람에게 동적으로 가리킵니다.

this를 마스터하는 것은 모든 JavaScript 개발자에게 필수적입니다. 왜냐하면 this가 함수가 접근할 수 있는 데이터를 결정하기 때문입니다. 잘못 이해하면 코드가 원인 모를 오류로 깨지고, 올바르게 이해하면 객체‑지향 JavaScript의 전체 힘을 활용할 수 있습니다.

this는 실제로 무엇을 나타내나요?

JavaScript에서 this는 현재 코드를 실행하고 있는 객체를 가리킵니다. 이를 함수를 호출한 사람이라고 생각하면 됩니다. 그 값은 작성 시에 고정되지 않고, 함수가 어떻게 그리고 어디서 호출되는지에 따라 동적으로 결정됩니다.

핵심 원칙

  • 실행 환경 (브라우저 vs. Node.js)
  • 호출 컨텍스트 (메서드 호출, 일반 함수 호출 등)
  • strict mode vs. non‑strict mode

this in the Global Context

전역 스코프에서 this는 전역 객체를 가리킵니다.

// Browser environment
console.log(this); // → window object

// Node.js environment
console.log(this); // → {} (empty object)

// The type is always "object"
console.log(typeof this); // → "object"

Summary: 전역 스코프에서 this는 환경의 전역 객체와 같습니다.

this 객체 내부 (메서드 호출)

함수가 객체의 메서드로 호출될 때, this는 그 객체를 가리킵니다.

const person = {
    name: "Ritam",
    greet() {
        console.log(`Hello, I'm ${this.name}!`);
    }
};

person.greet(); // → "Hello, I'm Ritam!"

규칙: obj.method()에 대해, this = obj.

this 일반 함수 내부

비‑엄격 모드

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

regularFunc(); 
// Browser → window object
// Node.js → global object (or empty object)

엄격 모드

"use strict";
function strictFunc() {
    console.log(this);
}

strictFunc(); // → undefined (both environments)

일반 함수에서는 this가 함수가 호출되는 방식에 따라 결정됩니다. 엄격 모드에서는 일반 호출 시 undefined가 반환됩니다.

this in Arrow Functions

Arrow functions lexically inherit this from their surrounding scope.

// Node.js environment
const arrowTest = () => console.log(this);
arrowTest(); // → {} (empty object)

// Browser environment
arrowTest(); // → window object

Nested Functions Inside Objects

Regular nested functions lose the outer this:

const calculator = {
    value: 100,
    calculate() {
        function innerFunc() {
            console.log(this.value); // → undefined!
        }
        innerFunc();
    }
};

calculator.calculate(); // undefined

Solution: Use an arrow function for the inner function so it inherits the outer this.

const calculatorFixed = {
    value: 100,
    calculate() {
        const innerFunc = () => {
            console.log(this.value); // → 100
        };
        innerFunc();
    }
};

calculatorFixed.calculate(); // Works perfectly!

일반적인 함정과 해결책

분리된 메서드 호출

const user = {
    name: "Ritam",
    sayHello() {
        console.log(`Hi from ${this.name}`);
    }
};

// Method call → this = user
user.sayHello(); // → "Hi from Ritam"

// Detached function call → this = global/undefined
const hello = user.sayHello;
hello(); // → "Hi from undefined"

메서드를 객체에서 추출하면 원래의 this 바인딩을 잃어버립니다.

우회 방법

  • bind를 사용해 this를 영구히 설정합니다.
  • 외부 this가 필요한 콜백에는 화살표 함수를 사용합니다.
  • 오래된 코드베이스에서는 외부 컨텍스트를 변수에 저장합니다 (const self = this;).

다양한 컨텍스트에서 this 요약 표

컨텍스트브라우저 (비엄격 모드)Node.js (비엄격 모드)엄격 모드
전역window{} (빈 객체)undefined
객체 메서드객체 자체객체 자체객체 자체
일반 함수 호출windowglobal / {}undefined
화살표 함수렉시컬 this (상속)렉시컬 this (상속)렉시컬 this (상속)

핵심 요점

  • “호출자”를 생각하라: this는 함수를 호출한 사람과 동일합니다.
  • 객체 메서드는 신뢰할 수 있다: obj.method()는 언제나 thisobj에 바인딩합니다.
  • 화살표 함수는 상속한다: 외부 this가 필요한 콜백 및 중첩 함수에 이상적입니다.
  • 일반 함수에서 this에 의존하지 말라 호출 컨텍스트가 확실하지 않은 경우.
  • 구식 패턴: const self = this;는 ES6 이전 코드에서 컨텍스트를 유지할 수 있습니다.

this를 마스터하면 JavaScript 사용자를 JavaScript 설계자로 변모시킵니다. 다음에 그 교활한 키워드를 볼 때, 정확히 누구를 가리키는지 알게 될 것입니다!

0 조회
Back to Blog

관련 글

더 보기 »