Explaining the Bind Method in JavaScript

Functions in JavaScript are objects. As objects, functions possess methods, including the powerful Bind method. Bind is used for setting the this value in methods, borrowing methods of other objects and for currying functions. Bind method is primarily used to call a function with the this value set explicitly. It enables us to easily set which specific object will be bound to this when a function is invoked. The need for bind occurs when this keyword in a method is not bound to the object that we expect it to be bound to - usually calling that method from a receiver object.

    var person = {
        name: "Terry Smith", 
        age: 43,
        print: function (event) {
            console.log(this.name + ", age: " + this.age);	​
        }
    };

    ​//Invoke the person's print method on button's click event​
    $("button").click (person.print.bind(person));

In order to bind this to the Person object we use the bind method. Otherwise by default this is bound to the HTML button element. Bind also allows us to borrow methods.

    var plane = {
        name: "Airbus A380",
        age: 5
    };

    // We can borrow the print method from the person object to show the plane data.​
    plane.print = person.print.bind(plane);
    plane.print(); // Airbus A380, age: 5

The Bind method also enables us to curry a function. Function Currying or partial function application, is the use of a function (with one or more arguments) returning a new function with some of the arguments already set. The returned function has access to the stored arguments and variables of the outer function.

    function info(age, automatic, model) {
        var gears = automatic ? "automatic" : "manual";
        return model + ", " + age + " years old, " + gears;
    }

We can use the bind method to curry (preset one or more of the parameters) in our info function. The first argument of the bind method sets the this value.

    // Not using the "this" keyword in our info function and its value is null.​
    var automaticInfo = info.bind(null, 5, true);​
    automaticInfo("Audi"); // "Audi, 5 years old, automatic"​
Tags: