This

dev_sang·2022년 6월 26일
0

JavaScript

목록 보기
7/11

본 포스팅은 드림코딩 엘리님의 타입스크립트 강의 개인 복습용 포스팅입니다.

  • JavaScript외 다른 객체지향 프로그래밍 언어에서는 this란 class자신을 가리킨다.
  • JavaScript에서는 호출한 문맥에 따라 this가 가리키는 것이 동적으로 바뀔 수 있다.

먼저 아무 코드 없이 console.log(this)를 찍어보면

이렇게 window객체가 나온다.
browser환경에서는 window가 global객체이다.


함수 simpleFunc을 선언하여 this를 찍어보아도

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


함수 simpleFun의 this는 동일하게 window객체이다.
global환경에서 함수 호출은 window객체의 함수를 호출하는 것이다.



Counter라는 class를 만들어보자.
Counter class내부의 increase함수는 this를 출력한다.

class Counter {
  counter = 0;
  increase = function () {
    console.log(this);
  };
}

위 Counter의 인스턴스 객체 counter을 생성한다. 그리고 counter의 increase함수를 호출한다.

const counter = new Counter();
counter.increase(); 

counter의 increase함수의 this는 Coutner class를 가리킨다.
increase함수의 호출은 class Counter객체의 함수를 호출하는 것이기 때문이다.


그럼 caller라는 변수를 만들어 그 안에 counter객체(인스턴스)의 increase함수를 할당해보자.
그리고 caller를 호출한다.

const caller = counter.increase;
caller();

이때 caller의 this는 undefined가 출력된다.

couter인스턴스의 increase함수의 포인터를 caller변수로 할당하면서 this의 정보를 잃어버렸기 때문이다.

  • let과 const키워드로 선언한 변수는 window 객체에 등록되지 않는다.
  • caller를 호출하는 객체는 window객체도, Couter class객체도 아니다.
  • 따라서 caller의 this는 undefined를 가리킨다.

caller 변수의 this가 Counter를 가리키도록 하려면 2가지 방법이 있다.
1. bind() 메서드를 사용한다.
2. arrow function을 사용한다.

먼저 bind()를 사용해보자.

const caller = counter.increase.bind(counter); // Counter

이렇게 .bind 함수의 인자로 묶어줄 객체를 넣으면 해당 객체의 this가 연결이 된다.

두번째로 arrow function을 사용하는 방법이다.
class Counter의 increase함수를 funcion키워드를 사용하는 함수 선언방식이 아니라, 그냥 아래 코드처럼

class Counter {
  counter = 0;
  increase = () => {
    console.log(this);
  };
}

이렇게 arrow function으로 바꿔주면 된다.


위 두 방법 중 하나로 사용하고, caller(); 를 호출하면 아래처럼 Counter 객체가 출력된다.


profile
There is no reason for not trying.

0개의 댓글