What is the use of the JavaScript 'bind' method?

后端 未结 19 1934
自闭症患者
自闭症患者 2020-11-21 06:24

What is the use of bind() in JavaScript?

19条回答
  •  灰色年华
    2020-11-21 06:33

    bind allows-

    • set the value of "this" to an specific object. This becomes very helpful as sometimes this is not what is intended.
    • reuse methods
    • curry a function

    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.

    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

    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
    

提交回复
热议问题