JavaScript - bind() method

revision:


Category : function.prototype

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.

The bind() method is reminiscent of call() and apply(). But instead of executing a function immediately, bind() returns a function that can be executed later on.

Syntax :

        bind(thisArg)
        bind(thisArg, arg1)
        bind(thisArg, arg1, arg2)
        bind(thisArg, arg1, arg2, /* …, */ argN)
    

Parameters

thisArg : the value to be passed as the "this" parameter to the target function "func" when the bound function is called. If the function is not in strict mode, "null" and "undefined" will be replaced with the global object, and primitive values will be converted to objects. The value is ignored if the bound function is constructed using the "new" operator.

arg1, …, argN : optional; arguments to prepend to arguments provided to the bound function when invoking "func".

Examples

            "use strict"; // prevent `this` from being boxed into the wrapper object
            function log(...args) {
                console.log(this, ...args);
            }
            const boundLog = log.bind("this value", 1, 2);
            const boundLog2 = boundLog.bind("new this value", 3, 4);
            boundLog2(5, 6); // "this value", 1, 2, 3, 4, 5, 6

            const module = {
                x: 42,
                getX: function() {
                  return this.x;
                }
              };
              
              const unboundGetX = module.getX;
              console.log(unboundGetX()); // The function gets invoked at the global scope
              // Expected output: undefined
              
              const boundGetX = unboundGetX.bind(module);
              console.log(boundGetX());
              // Expected output: 42
              
        

Practical examples

example: bind() method

code:
                        <div class="spec">
                            <p id="three"></p>
                        </div>
                        <script>
                            var obj = { num: 4 };
                            function add(a, b){
                                return this.num + a + b;
                            }
                            const func = add.bind(obj, 3, 5);
                            document.getElementById("three").innerHTML = func();
                        </script>
                

example: use bind() to create a bound function

code:
                    <div class="spec">
                        <p id="nine"></p>
                        <p id="ten"></p>
                        <p id="eleven"></p>
                    </div>
                    <script>
                        this.x = 9;   // 'this' refers to global 'window' object here in a browser
                        const module = {
                            x: 81,
                            getX: function() { return this.x; }
                        };
            
                        module.getX();
                        document.getElementById("nine").innerHTML = module.getX();
            
                        const retrieveX = module.getX;
                        retrieveX();
                        document.getElementById("ten").innerHTML = retrieveX(); 
                        //  the function gets invoked at the global scope x'
                        
                        const boundGetX = retrieveX.bind(module);
                        boundGetX();
                        document.getElementById("eleven").innerHTML = boundGetX();
                    </script>
                

example: use bind() to make SetTimeout work

code:
                    <div class="spec">
                        <p id="twelve"></p>
                    </div>
                    <script>
                        let user = {
                            firstName: "John"
                        };
                        function funct() {
                            document.getElementById("twelve").innerHTML = this.firstName;
                            }
            
                            let funcUser = funct.bind(user);
                            funcUser(); // John
                    </script>
                

example: create 2 objects; the member object borrows the fullname method from person

code:
                    <div class="spec">
                        <p id="bind_A"></p>
                    </div>
                    <script>
                        const person = {
                            firstName:"John",
                            lastName: "Doe",
                            fullName: function() {
                                return this.firstName + " " + this.lastName;
                            }
                        }
                        const member = {
                        firstName:"Hege",
                        lastName: "Nilsen",
                        }
                        let fullName = person.fullName.bind(member);
                        document.getElementById("bind_A").innerHTML = fullName();
                    </script>