You don’t need to remember to bind your functions every time.

One of the things we love the most about JavaScript is how most of the times we don’t know where this points to (yeah right, we love that). Take for example this simple bit of code:

Creating a new Foo instance and calling doStuff() on it will get you “baz” logged to the console as expected. So in this case we actually know where this is pointing to and what to expect. We are sure this works:

But what would happen if we call foo.doStuff() from a different context, let’s say an event or as a callback passed to setTimeout()? We would get undefined logged instead of the expected baz because in this case this is not pointing to our foo instance as we would expect (yay JavaScript!):

One way to solve this is by telling the function where this should be pointing to using the Function.prototype.bind method. So, if we replace the last line of the previous snippet with something like this, we get the correct bits logged to the console:

setTimeout(foo.doStuff.bind(foo), 500); // Logs "baz", we're good

Now it works but we will need to remember to do this every time we call Foo.doStuff from a similar context, and nobody ain’t got time for that(tm). Thanks to another handy JavaScript feature (function hoisting) we can wireup this binding in the constructor and forget about doing it every time the function is called.

We added the bind call at line 5 and now whenever Foo.doStuff is called, we know for sure that this will point to a Foo instance and you don’t have to bind the function every time because it’s already bound in the constructor. Pretty neat, eh?

Since we’re in this subject, I suggest you take look at these links if you haven’t already:

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.