[JS] bind, call, apply

IRE_0546·2021년 9월 8일
0

JavaScript 정복

목록 보기
2/2

binding이란?

자바스크립트 함수는, 각자 자신만의 this를 정의한다.

  • 그렇다면 this란?
    예를 들어, Console.log로 this를 확인해보면 window 객체 하나가 나타나는 것을 볼 수 있다. 그렇다고 해서 this 객체가 꼭 윈도우 객체는 아니다. 객체 내부 메서드 호출 시, 생성자 new 호출 시, 명시적 bind에 따라 이 객체가 무엇인지 바뀌게 된다.

이것을 단순히 window 객체로만 쓰고 싶지는 않을 것이다. 당연히, 용도에 맞게 this를 알맞은 형태로 바꿔서 사용하고 싶다. 이러한 작업을 하는 것이 this binding이다.

즉, 이러한 this를 window가 아닌 다른 객체로 바꿔주는 역할을 하는 함수가 bind, call, apply이다.

이들의 차이를 간단히 정리해 보자면 아래와 같다.

call & apply

함수를 호출하는 함수이다. 첫 번째 인자에 this로 세팅하고 싶은 객체를 넘겨주고 this를 바꾸고 나서 실행한다.

  • call & apply 차이점?
    첫번째 인자를 제외하고 (this를 대체할 값) 두 번째 이후의 다른 파라미터를 입력하는 방식이 다르다. 차이는 아래의 예제를 참고하면 된다.
const Object = { name: "dodogim"};

const introduction = function(hobby) {
	console.log(`my name is ${this.name}, My hobby is ${hobby}`);
}

introduction("piano"); //my name is , My hobby is piano
introduction.call(Object, "piano"); //my name is dodogim, My hobby is piano
introduction.apply(Object, ["piano"]); //my name is dodogim, My hobby is piano

call : 그냥 넣어도 된다.
apply: 두 번째 인자부터는 모두 배열에 넣어야 한다.

bind

const result = introduction.bind(Object);
result("piano"); //my name is dodogim, My hobby is piano 

bind 함수와 앞의 call, apply와 다른 점은 함수를 '실행하지 않는다는' 점이다. 대신 bound 함수를 리턴하는데 위의 코드와 같이 동작한다. 예제와 같이 매핑하는 순간부터 Object로 가지고 있기 때문에 후에 사용해도 된다. 나머지 파라미터 설정은 call과 apply와 동일하다.

profile
Front-end developer, Time is flying never to return ✨

0개의 댓글