• 카테고리

    질문 & 답변
  • 세부 분야

    풀스택

  • 해결 여부

    미해결

id 넘겨주는 부분 bind

21.07.14 01:56 작성 조회수 111

0

아이디를 넘겨주는 곳에서 bind로 id 값을 바인딩 해주면 어떨까요?

{isEditing ? <MsgInput mutate={onUpdate.bind(null, id)} text={text} /> : text}
<button onClick={startEdit.bind(null, id)}>Fix</button>

답변 1

답변을 작성해보세요.

1

bind를 사용하셔도 됩니다.
둘의 차이는 거의 없이 동일하게 동작합니다.

둘 모두 render영역 내에서 생성하므로 매 랜더시마다 새롭게 생성되는 함수라는 점에서
성능을 떨어뜨리는 요인이 될 수 있다고 보는 사람들도 있지만
어지간히 규모가 큰 함수가 아닌 이상에는 유의미한 성능저하는 없다고 봐도 됩니다.


둘을 굳이 비교하면 다음과 같은 약간의 차이점들이 있긴 합니다.

const updateCallback = (id) => {}
  1. console.dir(updateCallback.bind(null, 1))
  2. <slot style="box-sizing:border-box;min-width:0px;min-height:0px"><span class="console-object object-value-function" style="box-sizing:border-box;min-width:0px;min-height:0px;white-space:pre-wrap;word-break:break-all;font-style:italic" tabindex="-1"><span style="box-sizing:border-box;min-width:0px;min-height:0px"><span class="object-value-function-prefix" style="box-sizing:border-box;min-width:0px;min-height:0px;color:#d0d6fb">ƒ </span>bound updateCallback()</span><span class="object-state-note info-note" style="box-sizing:border-box;min-width:0px;min-height:0px;background-color:#99aaff;display:inline-block;width:11px;height:11px;color:#949494;text-align:center;border-radius:3px;line-height:13px;margin:0px 6px;font-size:9px"></span></span></slot>
    1. arguments(...)
    2. caller(...)
    3. length0
    4. name"bound updateCallback"
    5. [[BoundThis]]null

console.dir(() => updateCallback(1))
  1. <slot style="box-sizing:border-box;min-width:0px;min-height:0px"><span class="console-object object-value-function" style="box-sizing:border-box;min-width:0px;min-height:0px;white-space:pre-wrap;word-break:break-all;font-style:italic" tabindex="-1"><span style="box-sizing:border-box;min-width:0px;min-height:0px">anonymous()</span><span class="object-state-note info-note" style="box-sizing:border-box;min-width:0px;min-height:0px;background-color:#99aaff;display:inline-block;width:11px;height:11px;color:#949494;text-align:center;border-radius:3px;line-height:13px;margin:0px 6px;font-size:9px"></span></span></slot>
    1. arguments(...)
    2. caller(...)
    3. length0
    4. name""
    5. [[FunctionLocation]]VM8570:1

1) bind에 의해 생성된 bound함수는 name 프로퍼티가 존재하는 반면
arrow함수는 name 프로퍼티가 비어있는 익명함수입니다.
따라서 bound함수가 디버깅시 추적에 상대적으로 용이하다는 장점이 있는데,
최근의 브라우저들은 위치까지 정확히 표기해주고 있어서 실제로는 큰 차이를 보이지는 않습니다.

2) bind 사용시에는 원본함수에 '오직 매개변수를 넘기기 위한 목적일 경우'에도
thisArg 자리를 비울 수가 없어 부득이 null 같은 무의미한 값을 넘겨줘야 합니다.
한편 arrow함수는 낭비되는 요소가 없습니다.

개인적으로는 arrow 함수를 선호합니다.
null을 넘겨주지 않아도 되며, 가독성도 더 뛰어나다고 생각하기 때문인데,
이는 어디까지나 개인의 취향이며,
질문자님 취향 및 팀 분위기에 따라 취사선택하시면 되겠습니다. :)

추가) bound 함수의 [[TargetFunction]], [[BoundThis]], [[BoundArgs]] 와
arrow 함수의 [[FunctionLocation]] , [[Scopes]] 정보는
크롬 브라우저에서 자체적으로 구현한 내용으로
다른 브라우저들에서는 다른 방식으로 표현하거나, 아예 노출하지 않고 있습니다.