Last Updated: February 25, 2016
·
405
· brandturner

_.bind() and Function.prototype.bind()

My oft-delayed quest to master Javascript has been met with bits of procrastination lately. It's days like these that I miss being a full-time student. I had the time to really learn a subject thoroughly instead of learning bits and pieces at a time while having to focus on work full time. Now that I'm wearing my big boy pants, I guess I can't complain.

So, while working with backbone.js (which includes underscore.js, which is now a glorified polyfill. How I'm surviving as a JS developer is beyond me), I came across the _.bind function quite a bit.

I asked one of our resident JS wizards (thanks Kamol) what the function actually does. Whenever you create a new function, class, etc. or otherwise change your scope, the value of this is changed/overwritten/destroyed (I don't know exactly what happens in memory). this always refers to the local scope.

For example:
var func = function(greeting){ return greeting + ': ' + this.name };
func = _.bind(func, {name: 'moe'}, 'hi');
func();
=> 'hi: moe'

The object {name: 'moe'} is now bound to the anonymous function. Even if this.name was set to James in the global scope, now that the function is bound to the object {name:'moe'}, func() will result in "hi: moe" and not "Hi: James".

The most useful takeaway from this esoteric subject for now is that it allows me to pass this into another scope and not have this be redefined whenever a new scope is created. That's how we pass our controller around.