Programming/Web

[JavaScript] call, apply, bind

goakgoak 2020. 4. 1. 21:47

call

func.call( this, arg1, arg2,... )

 

call 메서드는 모든 함수에서 사용할 수 있으며 this를 특정값으로 지정할 수 있다.

 

- this : 지정 객체

- arg1, arg2 : 객체를 위한 인수

 

apply

func( this, [ argsArray ] )

 

apply 메서드는 call의 역할과 완전히 같지만, 인수를 배열로 전달한다.

 

- this : 지정 객체

- [argsArray] : 객체를 위한 인수 배열

 

bind

func.bind( this, arg1, arg2,... )

 

bind 메서드는 함수의 this 값을 영구히 바꿀 수 있다. bind 메서드를 호출하면 this를 받으면서 새 함수를 리턴한다.

 

- this : 지정 객체

- arg1, arg2 : 객체를 위한 인수

 

 

bind, 언제 사용하나요?

setTimeout에 메서드를 전달할 때 처럼, 객체 메서드를 콜백으로 전달할 때 this 정보가 사라지는 문제가 생긴다.

 

1
2
3
4
5
6
7
8
9
10
var healthObj = {
  name : "달리기",
  lastTime : "PM10:12",
  showHealth : function() {
    setTimeout(function() {
        console.log(this.name + "님, 오늘은 " + this.lastTime + "에 운동을 하셨네요");      
    }, 1000)
  }
}
healthObj.showHealth();
cs

 

위 예시의 실행결과는 `undefined`가 되는데 그 이유는 setTimeout 메서드에서 this에 window를 할당하기 때문이다.

따라서 this.name은 window.name이 되는데 window에는 name과 lastTime이 없으므로 undefined가 출력된다.

 

 

1
2
3
4
5
6
7
8
9
10
healthObj.showHealth();var healthObj = {
  name : "달리기",
  lastTime : "PM10:12",
  showHealth : function() {
    setTimeout(function() {
        console.log(this.name + "님, 오늘은 " + this.lastTime + "에 운동을 하셨네요");      
    }.bind(this), 1000)
  }
}
healthObj.showHealth();
cs

 

이때 bind 메서드를 사용하면 컨텍스트를 고정하여 setTimeout에 넘길 수 있다.

 

 

+)

또 다른 방법으로는 익명 함수를 사용하는 방법도 있지만 setTimeout이 트리거 되기 전에 context가 변경되는 경우에는 의도와 다른 결과를 초래할 수 있다.

 

 

 

출처

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

- https://ko.javascript.info/bind