본문 바로가기

JS

bind()

객체로부터 메서드를 추출하고 나중에 그 메서드를 호출하고 객체의 this를 사용하길 예상한다. 그러나 객체는 사라진다. 함수로부터 바운딩 함수를 생성하면, 문제를 해결할 수 있다.


1
2
3
4
5
6
7
8
9
10
11
12
13
    this.x = 9;    // this refers to global "window" object here in the browser
    var module = {
      x: 81,
      getX: function() { return this.x; }
    };
 
    console.log(module.getX()); // 81
 
    var retrieveX = module.getX;
    console.log('without binding',retrieveX());   
  
    var boundGetX = retrieveX.bind(module);
    console.log('with binding',boundGetX()); // 81
cs


1줄에서 this.x = 9의 의미는 window 객체의 x에 9를 할당한 것이다.

module 객체의 x에는 81이 들어갔고, getX 함수는 module의 x를 반환한다.


module에 접근해서 getX를 호출하면 81이 나온다.


module의 getX 함수를 retrieveX에 할당하면 module 객체가 사라진다. 그래서 window의 x 값인 9가 출력된다.


이를 방지하기 위해 boundGetX에 module의 함수를 할당할 때 bind() 함수를 써서 module 객체를 묶어준다. 바인딩을 하게 되면 지정한 객체를 잃지 않고 접근할 수 있다.



매달 비용을 차감하는 함수가 있다고 할 때.

For example, you have a function to deduct monthly club fees

function getMonthlyFee(fee){
  var remaining = this.total - fee;
  this.total = remaining;
  return this.name +' remaining balance:'+remaining;
}

Now you want to reuse this function for a different club member. Note that the monthly fee will vary from member to member.

다른 멤버들을 위해 이 함수를 재사용 하길 원한다. 멤버마다 월 비용이 다르다.

Let's imagine Rachel has a balance of 500, and a monthly membership fee of 90.

레이첼이 500을 갖고 있고 매달 90이 비용이다.

var rachel = {name:'Rachel Green', total:500};

Now, create a function that can be used again and again to deduct the fee from her account every month

그녀의 계좌에서 매달 돈이 빠져나가게 하는 함수를 생성한다.

//bind
var getRachelFee = getMonthlyFee.bind(rachel, 90);
//deduct
getRachelFee();//Rachel Green remaining balance:410
getRachelFee();//Rachel Green remaining balance:320

Now, the same getMonthlyFee function could be used for another member with a different membership fee. For Example, Ross Geller has a 250 balance and a monthly fee of 25

같은 getMonthlyFee 함수가 다른 멤버십 비용을 가진 다른 멤버에게 사용될 수 있다. 로스 겔러는 250을 갖고 있고 매달 25를 낸다.

var ross = {name:'Ross Geller', total:250};
//bind
var getRossFee = getMonthlyFee.bind(ross, 25);
//deduct
getRossFee(); //Ross Geller remaining balance:225
getRossFee(); //Ross Geller remaining balance:200

getMonthlyFee 함수에 바인딩을 할 때 첫 인수는 객체 이름, 두번째는 함수의 인자이다.

함수에서 this로 접근할 때 바인딩된 객체의 total에 접근할 수 있다.


https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind


http://plnkr.co/edit/mhWJVIwOwPTOaKViqCL7?p=preview


https://stackoverflow.com/questions/2236747/use-of-the-javascript-bind-method