Question:

The JavaScript bind method returns a different function set to a specified context. Explain how this function works and give at least one example of its usage.


“bind” is a method we use in JavaScript to explicitly bind this to any object we choose. It also has the benefit of hard binding so that this can’t lose it’s reference like call and apply can.

function foo(something) {
    console.log( this.a, something );
    return this.a + something;
}

var obj = {
    a: 2
};

var bar = foo.bind( obj ); // use bind to force foo this to reference obj

var b = bar( 4 ); // 2 4  
console.log( b ); // 5

In the above example you can see that by using bind we can set up foo’s this to point to obj. Then we can use bar as a function and pass it a parameter then pass that to variable b and log that output. Bind is different from apply and call in that it returns another function that doesn’t execute immediately we have to invoke it first. This can be useful for onClick events where we don’t know when they’ll be clicked on but know what context we want them to have. That concludes this article on bind.