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

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

What is the use of bind() in JavaScript?

相关标签:
19条回答
  • 2020-11-21 06:45

    bind is a function which is available in java script prototype, as the name suggest bind is used to bind your function call to the context whichever you are dealing with for eg:

        var rateOfInterest='4%';
        var axisBank=
        {
        rateOfInterest:'10%',
        getRateOfInterest:function()
        {
        return this.rateOfInterest;
        }
        }
        axisBank.getRateOfInterest() //'10%' 
    
    
        let knowAxisBankInterest=axisBank.getRateOfInterest // when you want to assign the function call to a varaible we use this syntax
        knowAxisBankInterest(); // you will get output as '4%' here by default the function is called wrt global context
    
    let knowExactAxisBankInterest=knowAxisBankInterest.bind(axisBank);     //so here we need bind function call  to its local context
    
    
        knowExactAxisBankInterest() // '10%' 

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

    I will explain bind theoretically as well as practically

    bind in javascript is a method -- Function.prototype.bind . bind is a method. It is called on function prototype. This method creates a function whose body is similar to the function on which it is called but the 'this' refers to the first parameter passed to the bind method. Its syntax is

         var bindedFunc = Func.bind(thisObj,optionsArg1,optionalArg2,optionalArg3,...);
    

    Example:--

      var checkRange = function(value){
          if(typeof value !== "number"){
                  return false;
          }
          else {
             return value >= this.minimum && value <= this.maximum;
          }
      }
    
      var range = {minimum:10,maximum:20};
    
      var boundedFunc = checkRange.bind(range); //bounded Function. this refers to range
      var result = boundedFunc(15); //passing value
      console.log(result) // will give true;
    
    0 讨论(0)
  • 2020-11-21 06:48

    Creating a new Function by Binding Arguments to Values

    The bind method creates a new function from another function with one or more arguments bound to specific values, including the implicit this argument.

    Partial Application

    This is an example of partial application. Normally we supply a function with all of its arguments which yields a value. This is known as function application. We are applying the function to its arguments.

    A Higher Order Function (HOF)

    Partial application is an example of a higher order function (HOF) because it yields a new function with a fewer number of argument.

    Binding Multiple Arguments

    You can use bind to transform functions with multiple arguments into new functions.

    function multiply(x, y) { 
        return x * y; 
    }
    
    let multiplyBy10 = multiply.bind(null, 10);
    console.log(multiplyBy10(5));

    Converting from Instance Method to Static Function

    In the most common use case, when called with one argument the bind method will create a new function that has the this value bound to a specific value. In effect this transforms an instance method to a static method.

    function Multiplier(factor) { 
        this.factor = factor;
    }
    
    Multiplier.prototype.multiply = function(x) { 
        return this.factor * x; 
    }
    
    function ApplyFunction(func, value) {
        return func(value);
    }
    
    var mul = new Multiplier(5);
    
    // Produces garbage (NaN) because multiplying "undefined" by 10
    console.log(ApplyFunction(mul.multiply, 10));
    
    // Produces expected result: 50
    console.log(ApplyFunction(mul.multiply.bind(mul), 10));

    Implementing a Stateful CallBack

    The following example shows how using binding of this can enable an object method to act as a callback that can easily update the state of an object.

    function ButtonPressedLogger()
    {
       this.count = 0;
       this.onPressed = function() {
          this.count++;
          console.log("pressed a button " + this.count + " times");
       }
       for (let d of document.getElementsByTagName("button"))
          d.onclick = this.onPressed.bind(this);
    }
    
    new ButtonPressedLogger();      
    <button>press me</button>
    <button>no press me</button>

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

    Simple Explanation:

    bind() create a new function, a new reference at a function it returns to you.

    In parameter after this keyword, you pass in the parameter you want to preconfigure. Actually it does not execute immediately, just prepares for execution.

    You can preconfigure as many parameters as you want.

    Simple Example to understand bind:

    function calculate(operation) {
      if (operation === 'ADD') {
       alert('The Operation is Addition');
      } else if (operation === 'SUBTRACT') {
       alert('The Operation is Subtraction');
      }
    }
    
    addBtn.addEventListener('click', calculate.bind(this, 'ADD'));
    subtractBtn.addEventListener('click', calculate.bind(this, 'SUBTRACT'));
    
    
    0 讨论(0)
  • 2020-11-21 06:49

    Bind creates a new function that will force the this inside the function to be the parameter passed to bind().

    Here's an example that shows how to use bind to pass a member method around that has the correct this:

    var myButton = {
      content: 'OK',
      click() {
        console.log(this.content + ' clicked');
      }
    };
    
    myButton.click();
    
    var looseClick = myButton.click;
    looseClick(); // not bound, 'this' is not myButton - it is the globalThis
    
    var boundClick = myButton.click.bind(myButton);
    boundClick(); // bound, 'this' is myButton
    

    Which prints out:

    OK clicked
    undefined clicked
    OK clicked
    

    You can also add extra parameters after the 1st (this) parameter and bind will pass in those values to the original function. Any additional parameters you later pass to the bound function will be passed in after the bound parameters:

    // Example showing binding some parameters
    var sum = function(a, b) {
      return a + b;
    };
    
    var add5 = sum.bind(null, 5);
    console.log(add5(10));
    

    Which prints out:

    15
    

    Check out JavaScript Function bind for more info and interactive examples.

    Update: ECMAScript 2015 adds support for => functions. => functions are more compact and do not change the this pointer from their defining scope, so you may not need to use bind() as often. For example, if you wanted a function on Button from the first example to hook up the click callback to a DOM event, the following are all valid ways of doing that:

    var myButton = {
      ... // As above
      hookEvent(element) {
        // Use bind() to ensure 'this' is the 'this' inside click()
        element.addEventListener('click', this.click.bind(this));
      }
    };
    

    Or:

    var myButton = {
      ... // As above
      hookEvent(element) {
        // Use a new variable for 'this' since 'this' inside the function
        // will not be the 'this' inside hookEvent()
        var me = this;
        element.addEventListener('click', function() { me.click() });
      }
    };    
    

    Or:

    var myButton = {
      ... // As above
      hookEvent(element) {
        // => functions do not change 'this', so you can use it directly
        element.addEventListener('click', () => this.click());
      }
    };
    
    0 讨论(0)
  • 2020-11-21 06:49

    In addition to what have been said, the bind() method allows an object to borrow a method from another object without making a copy of that method. This is known as function borrowing in JavaScript.

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