본문 바로가기
컴퓨터보안/웹클라이언트

JavaScript와 jQuery에서 `this`의 동작 원리 및 콜백 함수 내에서의 변화

by 데이빗제이2 2024. 6. 4.

 

JavaScript에서 this 키워드는 함수가 호출될 때의 실행 컨텍스트(또는 문맥)를 나타냅니다. 그러나 this는 함수가 호출되는 방식에 따라 다른 객체를 참조할 수 있습니다. 특히 콜백 함수 내에서 this가 어떻게 달라지는지 이해하는 것은 중요합니다. 이번 포스트에서는 이를 쉽게 설명하고, 예제와 함께 콜백 함수와 this의 변화를 다루어 보겠습니다.

1. JavaScript의 this 기본 동작

this 키워드는 객체의 메서드 내에서 해당 객체를 참조합니다. 하지만 전역 함수나 콜백 함수 내에서는 다른 객체를 참조할 수 있습니다. 예를 들어보겠습니다.

var myObject = {
    name: "My Object",
    
    sayName: function() {
        console.log(this.name); // this는 myObject를 참조합니다
    }
};

myObject.sayName(); // "My Object" 출력
        

위 예제에서 sayName 메서드 내의 thismyObject를 참조하므로 this.name은 "My Object"를 출력합니다.

2. 콜백 함수 내에서의 this

콜백 함수는 보통 다른 함수의 인자로 전달되어 특정 이벤트나 작업이 완료되면 실행됩니다. 이때 콜백 함수 내에서의 this는 호출 컨텍스트에 따라 달라집니다. 이를 이해하기 위해 setTimeout을 사용한 예제를 보겠습니다.

var myObject = {
    name: "My Object",
    
    makeRequest: function() {
        console.log("Outside callback:", this.name); // this는 myObject를 참조합니다

        setTimeout(function() {
            console.log("Inside callback:", this.name); // this는 전역 객체를 참조합니다 (브라우저에서는 window)
        }, 1000);
    }
};

myObject.makeRequest();
// "Outside callback: My Object"
// "Inside callback: undefined"
        

위 예제에서 makeRequest 메서드 내의 thismyObject를 참조하지만, setTimeout의 콜백 함수 내에서의 this는 전역 객체(window)를 참조합니다. 따라서 this.nameundefined를 출력합니다.

3. this 참조를 유지하는 방법: me 패턴

콜백 함수 내에서도 원래의 객체를 참조하기 위해 var me = this;와 같은 패턴을 사용할 수 있습니다. 이는 this의 값을 다른 변수(me)에 저장하여 콜백 함수 내에서 사용하도록 하는 방식입니다.

var myObject = {
    name: "My Object",
    
    makeRequest: function() {
        var me = this; // 현재 컨텍스트를 me에 저장
        console.log("Outside callback:", this.name); // this는 myObject를 참조합니다

        setTimeout(function() {
            console.log("Inside callback:", this.name); // this는 전역 객체를 참조합니다
            console.log("Inside callback with me:", me.name); // me는 myObject를 참조합니다
        }, 1000);
    }
};

myObject.makeRequest();
// "Outside callback: My Object"
// "Inside callback: undefined"
// "Inside callback with me: My Object"
        

위 예제에서 var me = this;를 사용하여 this의 값을 me에 저장한 후, 콜백 함수 내에서 me를 사용하면 원래의 객체를 참조할 수 있습니다.

4. jQuery와 AJAX 요청에서의 this

jQuery의 AJAX 요청에서도 콜백 함수 내에서 this의 동작은 동일하게 적용됩니다. AJAX 요청의 success 콜백 함수 내에서 this는 AJAX 설정 객체를 참조하게 됩니다. 이를 방지하고 원래 객체를 참조하려면 앞서 설명한 me 패턴을 사용하면 됩니다.

var myObject = {
    name: "My Object",
    
    makeRequest: function() {
        var me = this; // 현재 컨텍스트를 me에 저장

        $.ajax({
            url: 'https://jsonplaceholder.typicode.com/posts/1',
            type: 'GET',
            success: function(response) {
                console.log("Inside AJAX success callback:");
                console.log("this.name:", this.name); // this는 AJAX 설정 객체를 참조합니다
                console.log("me.name:", me.name);     // me는 myObject를 참조합니다
            }
        });
    }
};

myObject.makeRequest();
// "Inside AJAX success callback:"
// "this.name: undefined"
// "me.name: My Object"
        

위 예제에서 success 콜백 함수 내의 this는 AJAX 설정 객체를 참조하므로 this.nameundefined를 출력합니다. 반면, memyObject를 참조하므로 me.name은 "My Object"를 출력합니다.