[JS]bind, call, apply 차이점

K00·2023년 3월 7일
0
post-thumbnail

📗 call, apply 비교하기

  • 공통점 : 첫 번째 인자에 바인딩 할 this 값을 받는다.

  • 차이점 : 두 번째 인자부터 call은 일반 함수처럼 인자(argument)를 받음, apply는 배열 형태의 인자를 받음

    두 차이점의 비교는 두 번째 인자에 배열을 넣고 비교하면 알 수 있다.
    call()은 전달받은 "배열 그대로" 받아온다 반면에
    apply()는 인자로 넣은 "배열을 풀어서" 각각의 매개 변수로 받아온다.

const arr = [1,2,3]

function callFn(arr) { //[1,2,3]
  console.log(this,arr); 
}
function applyFn(idx1,idx2,idx3) { //1,2,3 <--
  console.log(this,idx1,idx2,idx3);
}

callFn.call("this값",arr) 
applyFn.apply("this값",arr)

//두 차이는 같은 배열을 인자로 전달 했을때 확인할 수 있다.
//call은 전달받은 "배열 그대로" 받아옴
//apply는 인자로 넣은 "배열을 풀어서" 하나하나의 매게 변수로 받아옴 

📕 bind

bind함수가 call, apply와 다른 점은 함수를 실행하지 않는다는 점이다. 대신 bound함수를 리턴한다. 이 bound함수(boundSay)는 이제부터 this를 obj로 갖고 있기 때문에 나중에 사용해도 된다. bind에 사용하는 나머지 rest 파라미터는 call과 apply와 동일하다.

function bindFn(pram) {
  console.log(this,pram);
}
let isBindFn = bindFn.bind("this값")
console.log(isBindFn("인자"));

🔎 bind()는 특정 함수를 더 짧게 만드는 용도로 사용할 수 있다.

js에서 우리는 데이터의 형태를 출력할거나 테스트할 때 console.log를 자주 사용한다.
하지만 이 console.log 를 자주 쓰는 상황에서는 이 구문도 길게 느껴질 수 있다.
이 경우, bind()를 사용해 짧은 함수로 만들 수 있다.

const log = console.log.bind(document);

log('test');      // test
log('helloooooo') // helloooooo

Reference

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

https://mong-blog.tistory.com/entry/call-apply-bind%EC%9D%98-%EC%B0%A8%EC%9D%B4

0개의 댓글