hanker

JavaScript - this 키워드 (현재 실행 중인 환경에 따라 다른 객체를 참조) 본문

JavaScript

JavaScript - this 키워드 (현재 실행 중인 환경에 따라 다른 객체를 참조)

hanker 2025. 1. 30. 00:00
반응형

이번 글에서는 JavaScript에서 가장 많이 헷갈리는 개념 중 하나인 this 키워드에 대해서 알아보자.

 

this는 실행 컨텍스트에 따라 다르게 동작하기 때문에 올바르게 이해하는 것이 중요하다!

 


1. this 란?

 

this 는 현재 실행 중인 컨텍스트에 따라 다른 객체를 참조하는 키워드이다.

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

 


2. this의 동작

 

- 기본적으로 전역 객체를 참조

- 객체의 메서드 내부에서는 해당 객체를 참조

- 화살표 함수에서는 부모 컨텍스트의 this를 상속

- 생성자 함수에서는 새로 생성된 객체를 참조

- call, apply, bind를 사용하면 this를 명시적으로 변경 가능

 

여기까지 정의를 알아보고 아래 코드에서 자세하게 알아보자.

 

 

2-1. 전역 공간에서의 this

console.log(this); 
// 브라우저에서는 'window'
// Node.js에서는 'global'
// 함수 내부에서의 this
function showThis() {
    console.log(this);
}
showThis(); 
// this는 window 또는 global을 참조
// use strict 모드에서는 undefined가 됨

 

 

2-2. 객체의 메서드 내부에서의 this

const obj = {
    name: "Alice",
    sayHello: function () {
        console.log(this.name);
    }
};
obj.sayHello(); // "Alice"

- 객체의 메서드 내부에서는 해당 객체(obj)를 참조

- this.name = "Alice"

// 객체 내부의 함수에서 this
const person = {
    name: "Bob",
    sayHello: function () {
        function innerFunction() {
            console.log(this.name);
        }
        innerFunction();
    }
};
person.sayHello(); // undefined

- 내부 함수에서는 this가 undefined가 됨

 

this를 유지하는 방법

방법1. this를 변수에 저장

const person = {
    name: "Charlie",
    sayHello: function () {
        const self = this;
        function innerFunction() {
            console.log(self.name);
        }
        innerFunction();
    }
};
person.sayHello(); // "Charlie"

 

방법2. 화살표 함수 사용(this를 상속)

const person = {
    name: "David",
    sayHello: function () {
        const innerFunction = () => {
            console.log(this.name);
        };
        innerFunction();
    }
};
person.sayHello(); // "David"

- 화살표 함수는 this를 부모 컨텍스트에서 상속받음

 

방법3. bind 사용

const person = {
    name: "Eve",
    sayHello: function () {
        function innerFunction() {
            console.log(this.name);
        }
        const boundFunction = innerFunction.bind(this);
        boundFunction();
    }
};
person.sayHello(); // "Eve"

- bind(this)를 사용하여 this를 강제로 설정

 

 

 

2-3. 생성자 함수에서 this

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

const john = new Person("John");
console.log(john.name); // "John"

- 생성자 함수에서는 this가 새로 생성된 객체를 가리킨다.

 

 

2-4. 화살표 함수에서 this

const obj = {
    name: "Foo",
    sayHello: () => {
        console.log(this.name);
    }
};
obj.sayHello(); // undefined

- 화살표 함수의 this는 객체를 가리키지 않고, 부모 스코프(window 또는 global)를 참조

- 화살표 함수 내부에서는 this가 바인딩되지 않는다.

 

 

2-5. call, apply, bind를 사용한 this 변경

- call 사용

function sayHello() {
    console.log(`Hello, my name is ${this.name}`);
}

const user = { name: "Jake" };
sayHello.call(user); // "Hello, my name is Jake"

 

- apply 사용

function introduce(age, city) {
    console.log(`I am ${this.name}, ${age} years old from ${city}.`);
}

const user = { name: "Lily" };
introduce.apply(user, [25, "New York"]); 
// "I am Lily, 25 years old from New York."

 

- bind 사용

function greet() {
    console.log(`Hi, I am ${this.name}`);
}

const user = { name: "Michael" };
const boundGreet = greet.bind(user);
boundGreet(); // "Hi, I am Michael"

 

* call과 apply는 즉시 실행, bind는 새로운 함수를 반환


3. this 정리
상황 this가 가리키는 대상
전역 공간 window (또는 global)
일반 함수 window (use strict 모드에서는 undefined)
객체의 메서드 해당 객체
객체 내부 함수 기본적으로 window, 해결방법 (self, bind, arrow function)
생성자 함수 새로 생성된 객체
화살표 함수 부모 컨텍스트의 this를 상속
call, apply, bind 사용 명시적으로 설정한 객체

 


정리

 

this는 실행 컨텍스트에 따라 다르게 동작하며, 화살표 함수는 부모의 this를 상속 받는다.

call, apply, bind를 사용하면 this를 원하는 객체로 지정 가능

 

끝.

반응형