[typescript] 메서드 내부에서의 this 사용하기

자바스크립트 및 타입스크립트에서 메서드 내에서 this 키워드를 사용하는 것은 종종 혼란스러울 수 있습니다. 이 글에서는 메서드 내에서 this를 사용하는 방법과 주의할 점에 대해 알아보겠습니다.

this 키워드란?

this 키워드는 메서드가 호출될 때 사용된 객체에 대한 참조를 제공합니다. 메서드가 호출될 때, this는 호출한 객체에 연결됩니다. 예를 들어, 다음과 같이 객체 내에서 메서드를 호출하면 this는 해당 객체를 가리킵니다.

const person = {
  name: "Alice",
  sayHello() {
    console.log(`Hello, my name is ${this.name}`);
  }
};

person.sayHello(); // 출력: "Hello, my name is Alice"

화살표 함수와 this

일반 함수와는 달리 화살표 함수 내에서는 자체적인 this가 없습니다. 화살표 함수는 함수가 선언된 당시의 this를 유지합니다. 따라서 화살표 함수 내에서 this를 사용하면 주변 범위의 this를 가져옵니다.

class MyClass {
  value = 42;

  printValue = () => {
    console.log(this.value);
  };
}

const obj = new MyClass();
obj.printValue(); // 출력: 42

bind, call, apply 메서드

this의 값을 강제로 지정하기 위해 bind, call, apply 메서드를 사용할 수 있습니다. 이를 통해 메서드가 호출될 때 this가 가리키는 객체를 지정할 수 있습니다.

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

const person1 = { name: "Alice" };
const person2 = { name: "Bob" };

const greetPerson1 = greet.bind(person1);
greetPerson1("Eve"); // 출력: "Hello, Eve. I am Alice"

greet.call(person2, "Eve"); // 출력: "Hello, Eve. I am Bob"

요약

이러한 내용을 숙지하면 메서드 내에서의 this를 올바르게 활용할 수 있을 것입니다.