Binding의 개념과 call, apply, bind
binding이란?
this를 binding한다. 이 말이 무슨 뜻일까?
javascript의 함수는 각자 자신만의 this라는 것을 정의한다. 예를 들어 자기소개를 하는 함수를 위해 say()이라는 함수를 만든다고 하자.
const say = function(){
console.log(this);
console.log("Hello, my name is" + this.name);
}
say();
실행결과는 다음과 같다.
window객체가 나타난다. 기본적으로 this는 window이기 때문이다.
하지만 무조건적으로 window라고 볼 수는 없다. this는 객체 내부, 객체 메서드 호출 시, 생성자 new 호출 시, 명시적 bind 시에 따라 바뀌기 때문이다.
this의 binding을 통해서 this를 원하는, 알맞은 객체로 바꿔줄 수 있다.
명시적으로 위의 this를 window가 아닌 다른 객체로 바꿔주는 함수가 call, apply, bind이다.
call과 apply
원래 함수는 선언한 후 호출해야 실행된다.
호출하는 방법으로는 함수 뒤에 ()를 붙이는 것, 그리고 call과 apply하는 방법이 있다.
다음은 say 함수이다.
cosnt say = function(city){
console.log(`Hello, my name is ${this.name}, I live in ${city}`);
}
const obj = {name:"Tom"};
say("seoul"); // Hello, my name is , I live in seoul
say.call(obj, "seoul"); // Hello, my name is Tom, I live in seoul
say.apply(obj, ["seoul"]); // Hello, my name is Tom, I live in seoul
call과 apply는 함수를 호출하는 함수이다. 첫 번째 인자에 this로 설정하고 싶은 객체를 넘겨주어 this를 바꾸고나서 실행한다.
첫 번째 실행의 경우 this에 아무런 setting이 되어있지 않으므로, this는 window 객체이다. 두 번째, 세 번째 실행의 경우 this를 obj로 변경시켰으므로 원하는 값이 나온다.
call과 apply의 첫 번째, this를 binding할 값을, 나머지에는 실제 say에 필요한 parameter를 입력하는 방식이다. call과는 다르게 apply함수는 두 번째 인자부터 모두 배열에 넣어야 한다.
또 다른 예이다.
var obj = {
string: 'zero',
yell: function() {
console.log(this.string);
}
};
var obj2 = {
string: 'what'
};
obj.yell(); // 'zero';
obj.yell.call(obj2); // 'what', obj1.yell()을 obj2.yell()로 바꾼 효과라고 보면 된다
obj.yell.apply(obj2); // 'what'
위의 코드의 obj.yell.call(obj2)로 this가 가리키는 것을 obj에서 obj2로 바꾸었다.
yell은 obj의 method임에도 불구하고 zero 대신 what으로 변경되었다.
즉 call을 써서 this를 정의해준다면 다른 객체의 parameter나 method를 자기 것마냥 사용할 수 있다.
<팁!>
- .call(this, paramter1, parameter2, ...)
- .apply(this, [paramter1, parameter2, ...])
bind
bind 함수가 call, apply와 다른 점은 함수를 실행하지 않는다는 점이다. 대신 bound 함수를 리턴한다. 이 bound 함수는 this를 설정한 함수이다. 또한 함수에 argument를 넣어 줄 수 있다.
const obj = {name: "nanana"};
const say = function(city){
console.log(`Hello, my name is ${this.name}, I live in ${city}`);
}
const boundSay = say.bind(obj);
const boundSayTwo = say.bind(obj,"busan");
boundSay("seoul");
boundSayTwo();
call, apply, bind 정리
call, apply, bind는 함수 호출 방법을 지정해서 this를 그때 그때 알맞은 객체로 명시적으로 바꿔주는 메소드이다.
call, apply와 bind의 차이점
- call, apply는 함수를 호출해서 인수 전달.
- bind 함수는 호출하지 않는다. this값을 유지하는 새로운 함수를 생성
call과 apply의 차이점
- call의 경우, 호출한 함수의 인수를 ,로 구분한 리스트 형식으로 전달
- apply는 배열 [ ]로 전달
출처
https://wooooooak.github.io/javascript/2018/12/08/call,apply,bind/
https://inpa.tistory.com/entry/JS-%F0%9F%93%9A-Call-Bind-Apply
https://velog.io/@dev_0livia/JavaScriptcall-apply-bind%EC%9D%98-%EC%B0%A8%EC%9D%B4