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

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

What is the use of bind() in JavaScript?

19条回答
  •  轮回少年
    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();      
    
    

提交回复
热议问题