JavaScript의 this

지은·2023년 6월 6일
0

JavaScript

목록 보기
39/42

this

: 실행 컨택스트 내에서 현재 실행 중인 함수나 메서드를 호출한 객체를 참조하는 특별한 키워드

  • this를 사용하여 해당 객체의 속성에 접근하거나 수정할 수 있다.
  • this의 값은 함수를 호출하는 방법에 따라 달라진다.
  • JavaScript의 모든 함수는 this를 가지고 있다. 함수가 호출되면, 그때그때 상황에 따라 동적으로 this가 결정된다. 이렇게 this가 동적으로 결정되는 것을 this가 어떤 객체에 바인딩(bind)된다고 한다.

실행 컨택스트(execution context)

: 코드가 실행되는 환경
실행 컨택스트는 코드 실행에 필요한 변수, 함수, 객체 및 스코프를 포함하고 있으며, 코드 실행 시 생성된다.


전역 컨택스트에서의 this

전역 컨택스트에서 this전역 객체를 참조하며, 브라우저에서는 window 객체이다.

console.log(this); // 전역 객체 (Window)
// Window {0: Window, 1: Window, window: Window, self: Window, document: document, name: '', location: Location, …}
function myFunction() {
  console.log(this); // 전역 객체 (Window)
}

myFunction();

객체의 메소드에서의 this

객체 메소드에서 this메소드를 호출한 객체를 참조한다.

const obj = {
  name: 'Jieun',
  printThis: function() { // ⚠ 화살표 함수로 작성하면 안됨
    console.log(this);
  }
}

obj.printThis(); // {name: 'Jieun', printThis: ƒ}

메소드를 다른 변수에 할당한 후 실행한 경우

이 경우 this는 호출되는 시점에 결정되는데, 전역 컨택스트에서 호출되었으므로 this전역 객체를 참조한다.

const printThisFunc = obj.printThis; // obj 객체의 메소드를 다른 변수에 할당

printThisFunc(); // 전역 객체 (Window)

반대로 전역 함수를 객체의 메소드에 할당하고 실행하면, this를 호출한 객체인 obj를 참조한다.

function printThisFunc() {
  console.log(this); // 전역 객체 (Window)
}

const obj = {
	name: 'Jieun',
    printThis: printThisFunc // 메소드에 할당
}

obj.printThis(); // {name: 'Jieun', printThis: ƒ}

bind() 메소드를 이용해 this를 특정 객체에 바인딩할 수도 있다.

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

const obj = {
	name: 'Jieun',
}

const bindedPrintThis = printThisFunc.bind(obj); // this에 obj를 바인딩한다.

bindedPrintThis(); // {name: 'Jieun'}

생성자 함수에서의 this

new 키워드로 생성자 함수를 호출할 떄, this새로 생성되는 객체를 참조한다.

function Person(name) {
  this.name = name;
  this.printThis = function() {
    console.log(this);
  }
}

const person1 = new Person('Jieun');
person1.printThis(); // Person {name: 'Jieun', sayHello: ƒ}

const person2 = new Person('GG');
person2.printThis(); // Person {name: 'GG', sayHello: ƒ}

화살표 함수에서의 this

화살표 함수는 자신만의 this를 갖지 않고, 자신을 포함하고 있는 상위 스코프에서 this 값을 상속한다.
그래서 객체 메소드를 선언할 때 화살표 함수로 작성해선 안되고, 일반 함수 표현식을 사용하는 것이 좋다.

const obj = {
  name: 'Jieun',
  printThis: () => {
    console.log(this);
  }
}

obj.printThis(); // 전역 객체 (Window)

아래의 예시에서 setTimeout 함수 내부의 화살표 함수는 자신을 포함하고 있는 외부 함수인 printThisthis를 상속받는다. 따라서 obj.printThis()를 호출할 때 obj 객체를 가리키게 된다.

const obj = {
  name: 'Jieun',          // 외부 스코프
  printThis: function() { // 외부 스코프
    setTimeout(() => {    
      console.log(this);  // 내부 스코프
    })
  }
}

obj.printThis(); // {name: 'Jieun', printThis: ƒ}

Strict Mode에서의 this

엄격 모드(Strict Mode)에서는 호출한 객체가 없을 경우, 기본값으로 Window 객체로 반환하지 않고 undefined를 반환한다.

'use strict';
function printThis() {
  console.log(this);
}

printThis(); // undefined
profile
개발 공부 기록 블로그

6개의 댓글

comment-user-thumbnail
2023년 6월 7일

잘 정리해주셨네요!! 잘 보고 갑니당 :)

답글 달기
comment-user-thumbnail
2023년 6월 7일

잘정리해주셨네요 고생하셨습니다~

답글 달기
comment-user-thumbnail
2023년 6월 8일

복습하고 갑니다 ~~!

답글 달기
comment-user-thumbnail
2023년 6월 11일

this 다시 정리하고 갑니당 ㅎㅎ

답글 달기
comment-user-thumbnail
2023년 6월 11일

this 잘보고 갑니다! JS 뿐만 아니라 다른 클래스형 언어들을 보면서 비교해보세요 그러면 좀 더 이해가 가드라구요

답글 달기
comment-user-thumbnail
2023년 6월 11일

this 깔끔한 정리 감사합니다~!

답글 달기