Header Image About a month ago, a link to this article called “How do you judge a Javascript programmer by only 5 questions?” was submitted to /r/javascript. One of the points they bring up in the article, is that people should know how to use the Function.prototype.bind function. Reading through a few comments on that thread, obviously some people didn’t understand how to use it or even why you’d use it. Let me explain.

Let’s say you want have the object Foo and you want to run the function bar every 5 seconds. So we’ll start off with:

function Foo(myName) {
    this.myName = myName;

Foo.prototype.bar = function() {
    console.log('Hey ' + this.myName + ', don\'t make it bad');

var foo = new Foo('Paul');

So then to start the interval, we’d do

setInterval(foo.bar, 5 * 1000);

You’d expect “Hey Paul, don’t make it bad” to print to console every 5 seconds? Well, it wouldn’t.

Hey undefined, don't make it bad
Hey undefined, don't make it bad
Hey undefined, don't make it bad

setInterval is calling your function through the Window object, so your this is actually the window. One ugly method I’ve seen people use is

setInterval(function() {
}, 5 * 1000;

Which would then print our desired output. But the much easier way is to use Function.prototype.bind. What it does, is basically what our second example does. It calls the function, but through your own object. So for our example above, we’d do

setInterval(foo.bar.bind(foo), 5 * 1000);

But .bind() goes a step further, allowing you to use any object for this. So you could do

setInterval(foo.bar.bind({myName: 'Jude'}), 5 * 1000);

Which would then output

Hey Jude, don't make it bad

For another example, let’s say we wanted to log a message to the console every second. What you’d use without .bind() would look like

setInterval(function() {
    console.log('Take a sad song and make it better');
}, 1000);

But if we used .bind(), we’d have it like

setInterval(console.log.bind(console, 'Take a sad song and make it better'), 1000);

So what that’s doing, is taking all args after the this argument, and passing them to the function.

More examples and a another (better) explanation can be found on MDN.