All tied up with Bind? I know the feeling - fifty shades of it.

It took me a while to understand what is going on with Bind. Reading the documentation a few times still left me wondering what was going on.

The bind() method creates a new function that, when called, has it's this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.  

That is quite a mouthful, and there is a lot going on with it. Bind permanently binds a context ("this" value) to a function. In essence Bind returns a duplicate of the target function with the context ("this") bound to it. Any references to "this" in the function will reference the context passed in.

To get a clearer idea of how it works lets rewrite the Bind function.

As before The bind() method creates a new function ... means that the bind function just returns a function:

Function.prototype.bind = function () {  
  return function () {

  }
}

Great, the basic structure is there - the function object now has a bind function, that returns a new function. Now lets set up the context. The purpose of bind is to permanently attach the context param (or the "this" parameter) to the function that bind is called on.

Now, as bind is called on a function like myFunction.bind(... we need to keep a reference to myFunction. Once we have the reference to the original function, we need to call it and pass the specified context to run it on, as well as any parameters that are passed.

Function.prototype.bind = function (context) {  
  var fn = this; //original bound function
  return function () {
    //get the arguments of the called bound function
    var args = Array.prototype.slice.call(arguments);
    //call the function (using "apply" in this case)
    return fn.apply(context, args);
  }
}

To recap what just happend, we start by creating a closure with a reference to the function being bound by using var fn = this;. At the moment "this" means nothing. "this" will refer to the function being bound to the left of the dot (.) when bind is called. return fn.apply(context, arguments); is the magic line that calls the bound function with the context parameter "this".

Hopefully we have a clearer idea of what is going on now. But why use it? Bound, what is you good for?

Because we can change the context of "this", we could capitalise on code reuse by using methods as stand alone functions.

Bind is also great for when we want to use a setTimeout without using an IIFE.

An example of both of the above in one:

var someObject = {  
  someAttribute: "Message",
  someFunction: function () {
    console.log(this.someAttribute);
  }
};

setTimeout(someObject.someFunction.bind(someObject), 1000);  

Here is a great article on understanding function prototype bind.

Oh, as an aside, you may have heard the term "Curry" or "Currying" too. Basically it is the same as the bind function.

Happy binding!