컴퓨터 공학/JavaScript

Function.bind(this, ...)가 필요한 경우

혼새미로 2022. 2. 16. 21:21
반응형

"A Raphael painting of Iron-Man playing Judo with Spider-Man" from DALL-E 2

예를 들어, 다음과 같이 두 함수 foo, bar가 있다고 하자.

 

const foo = (a: string, b: string, c: string) => {
    return `${a}-${b}-${c}`
}
const bar = (func: (a: string, b: string)=> string) => {
    return func('wow', 'amazing')
}

 

이때, bar의 파라미터로 foo를 넘겨주고 싶은데, 파라미터 개수가 다르다. 따라서, foo의 첫 번째 파라미터는 'world'로 고정하여 bar에 넘겨주고 싶을 때, Function.bind(this, ...)를 사용할 수 있다.

 

bar(foo.bind(this, 'world')) // wolrd-wow-amazing

 

foo.bind(this, 'world')를 다시 쓰면 아래와 같이 볼 수 있다.

 

const goo = (a: string, b: string) => {
    return `world-${a}-${b}`
}

 

즉, 아래의 두 코드는 같은 것이다.

 

bar(foo.bind(this, 'world')) == bar(goo)

 

End.

반응형