JavaScript/함수

[JavaScript]메서드와 this(Method and this)

DevStory 2022. 7. 4.

JavaScript에서 객체의 프로퍼티가 함수인 경우에는 해당 프로퍼티를 메서드라고 말합니다.

 

이번 포스팅은 메서드에서 this가 어떻게 동작하는지 설명합니다.


this 바인딩

메서드에 사용된 this는 메서드를 호출한 객체로 바인딩됩니다. 즉, 현재 객체를 나타냅니다.

 

다음 예제를 살펴봅시다.

let obj = {
  strValue: 'Hello',
  normalFunc: function() {
    console.log(this.strValue)
  }
}

obj.normalFunc(); // Hello

메서드의 this는 현재 객체를 나타내므로 this는 obj를 가리킵니다. 따라서, obj 객체의 strValue 프로퍼티의 값이 콘솔에 출력되었습니다.


다른 객체에 할당

다음 예제는 객체에 메서드를 동적으로 추가합니다.

let obj = {
  strValue: 'Hello',
  normalFunc: function() {
    console.log(this.strValue)
  }
};

let otherObj = {}; // 빈 객체 생성

otherObj.normalFunc = obj.normalFunc; // 메서드를 동적으로 추가
otherObj.normalFunc(); // undefined

위 예제를 실행하면 undefined가 출력됩니다. otherObj 객체에는 strValue라는 프로퍼티가 없기 때문이죠.

 

다음 예제는 otherObj 객체에 strValue 프로퍼티를 추가 후 메서드를 호출합니다.

let obj = {
  strValue: 'Hello',
  normalFunc: function() {
    console.log(this.strValue)
  }
};

let otherObj = {
  strValue: 'otherObj'
}; // strValue 프로퍼티가 존재하는 객체 생성

otherObj.normalFunc = obj.normalFunc; // 메서드를 다른 객체에 동적으로 추가
otherObj.normalFunc(); // otherObj
obj.normalFunc();      // Hello

이번에는 undefined가 아닌 otherObj 객체의 strValue 프로퍼티 값이 콘솔에 출력되었습니다.

 

즉, 메서드 내부에 사용된 this는 메서드를 호출한 객체를 나타냅니다.


객체 생성 후 함수 할당

다음 예제는 객체를 생성 후 프로퍼티에 함수를 할당합니다.

// this를 사용하는 함수를 선언
function normalFunc() {
  console.log(this.strValue);
}

// strValue 프로퍼티가 존재하는 객체를 생성
let obj = {
  strValue: 'Hello'
}; 

// 객체에 this를 사용하는 함수를 동적으로 추가
obj.func = normalFunc;
obj.func(); // Hello

만약, 객체에 함수를 할당하지 않고 그냥 호출했다면 this는 전역 객체를 가리키며, 아래 예제는 브라우저에서 실행했으므로 this는 window 객체를 가리킵니다.

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

normalFunc();

[실행 결과]

즉, 위 예제를 통해 this의 값은 런타임과 컨텍스트에 따라 결정된다는 것을 알 수 있습니다.


화살표 함수

다음 예제는 일반 함수가 아닌 화살표 함수로 구현된 메서드에서 this를 사용합니다.

let obj = {
  strValue: 'Hello',
  arrowFunc: () => { console.log(this.strValue) }
}

obj.arrowFunc(); // undefined

화살표 함수의 this는 메서드를 호출한 객체가 아닌 화살표 함수 외부의 this를 참조합니다.

 

다음 예제는 브라우저에서 실행되었습니다. 따라서, 화살표 함수의 this는 전역 객체인 window를 가리킵니다.

let obj = {
  strValue: 'Hello',
  arrowFunc: () => { console.log(this) }
}

obj.arrowFunc();

[실행 결과]

화살표 함수에 사용된 this가 함수 외부를 참조한다면, 화살표 함수를 일반 함수로 감싸면 무슨 값이 출력되는지 다음 예제를 통해 알아봅시다.

let obj = {
  strValue: 'Hello',
  normalFunc: function() {
    let arrowFunc = () => { console.log(this) }
    arrowFunc();
  }
}

obj.normalFunc();

[실행 결과]

화살표 함수의 this는 외부 함수인 normalFunc()의 this가 됩니다. 따라서, this는 normalFunc() 메서드를 호출한 객체입니다.


정리

  • 메서드의 this는 메서드를 호출한 객체를 가리킵니다.
  • this의 값은 런타임에 결정됩니다.
  • 화살표 함수의 this는 화살표 함수 외부 함수의 this입니다.
반응형

댓글