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

后端 未结 19 1964
自闭症患者
自闭症患者 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
    
    0 讨论(0)
  • 2020-11-21 06:33
    /**
     * Bind is a method inherited from Function.prototype same like call and apply
     * It basically helps to bind a function to an object's context during initialisation 
     * 
     * */
    
    window.myname = "Jineesh";  
    var foo = function(){ 
      return this.myname;
    };
    
    //IE < 8 has issues with this, supported in ecmascript 5
    var obj = { 
        myname : "John", 
        fn:foo.bind(window)// binds to window object
    }; 
    console.log( obj.fn() ); // Returns Jineesh
    
    0 讨论(0)
  • 2020-11-21 06:39

    As mentioned, Function.bind() lets you specify the context that the function will execute in (that is, it lets you pass in what object the this keyword will resolve to in the body of the function.

    A couple of analogous toolkit API methods that perform a similar service:

    jQuery.proxy()

    Dojo.hitch()

    0 讨论(0)
  • 2020-11-21 06:40

    From the MDN docs on Function.prototype.bind() :

    The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

    So, what does that mean?!

    Well, let's take a function that looks like this :

    var logProp = function(prop) {
        console.log(this[prop]);
    };
    

    Now, let's take an object that looks like this :

    var Obj = {
        x : 5,
        y : 10
    };
    

    We can bind our function to our object like this :

    Obj.log = logProp.bind(Obj);
    

    Now, we can run Obj.log anywhere in our code :

    Obj.log('x'); // Output : 5
    Obj.log('y'); // Output : 10
    

    This works, because we bound the value of this to our object Obj.


    Where it really gets interesting, is when you not only bind a value for this, but also for its argument prop :

    Obj.logX = logProp.bind(Obj, 'x');
    Obj.logY = logProp.bind(Obj, 'y');
    

    We can now do this :

    Obj.logX(); // Output : 5
    Obj.logY(); // Output : 10
    

    Unlike with Obj.log, we do not have to pass x or y, because we passed those values when we did our binding.

    0 讨论(0)
  • 2020-11-21 06:40

    Bind Method

    A bind implementation might look something like so:

    Function.prototype.bind = function () {
      const self = this;
      const args = [...arguments];
      const context = args.shift();
    
      return function () {
        return self.apply(context, args.concat([...arguments]));
      };
    };
    

    The bind function can take any number of arguments and return a new function.

    The new function will call the original function using the JS Function.prototype.apply method.
    The apply method will use the first argument passed to the target function as its context (this), and the second array argument of the apply method will be a combination of the rest of the arguments from the target function, concat with the arguments used to call the return function (in that order).

    An example can look something like so:

    function Fruit(emoji) {
      this.emoji = emoji;
    }
    
    Fruit.prototype.show = function () {
      console.log(this.emoji);
    };
    
    const apple = new Fruit('                                                                    
    0 讨论(0)
  • 2020-11-21 06:43

    The bind() method creates a new function instance whose this value is bound to the value that was passed into bind(). For example:

       window.color = "red"; 
       var o = { color: "blue" }; 
       function sayColor(){ 
           alert(this.color); 
       } 
       var objectSayColor = sayColor.bind(o); 
       objectSayColor(); //blue 
    

    Here, a new function called objectSayColor() is created from sayColor() by calling bind() and passing in the object o. The objectSayColor() function has a this value equivalent to o, so calling the function, even as a global call, results in the string “blue” being displayed.

    Reference : Nicholas C. Zakas - PROFESSIONAL JAVASCRIPT® FOR WEB DEVELOPERS

    0 讨论(0)
提交回复
热议问题