[Typescript] bind 메서드

김성수·2024년 2월 28일
0

typescript

목록 보기
1/1

typescript의 bind 메서드가 생소해서 기록해본다.

Example code

interface User{
  name: string;
}

const sam: User{name:"sam"};

function showName(this: User, age: number|undefined, gender: "m"|"f"){
 console.log(this.name, age, gender); 
}

const a = showName.bind(sam);
a(undefined, "m");

bind를 사용한 이유는 showName 메서드를 호출했을 때 this 키워드를 사용하여 값을 가져오고 싶기 때문이다.

기존에 존재하는 객체 데이터에서 새로운 property를 추가해 확장해 나가고 싶을 때 this 키워드로 기존 데이터는 고정적으로 가져가면서 확장해나가고 싶을 때 사용할 수 있다.

profile
깊이 있는 소프트웨어 개발자가 되고 싶습니다.

0개의 댓글