Hard binding ‘this’ in your code

There are times when you are scratching your head wondering how on earth the value of ‘this’ got changed. For example, if you are within a function called from an object, ‘this’ may point to that object. However, when the function is set as an event listener to a button, ‘this’ will be the button itself.

So how can you ensure that ‘this’ binding remains what you want it to be? Here is the code to do just that.

function bind(fn, obj) {
    // fn - Function to be hard binded
    // obj - Object to which the function 'fn' has to be binded
    return function() {
        fn.apply(obj, arguments); // Call site to call the function
    };
}

var obj = {
    bar: "bar",
    foo: function(x) {
        console.log(this.bar + ' value: ' + x);
    }
};

var obj2 = {
    bar: "bar2"
};

foo = bind(obj.foo, obj);

foo(3); // bar value: 3

foo = bind(obj.foo, obj2);

foo(3); // bar2 value: 3

foo.call(obj2); // This too gives 'bar' since foo has been hard binded now. Hence this is no longer the call site.

Thankfully, ES5 onwards, this 'bind' feature is built in to Javascript. Here is the MDN page for that where you can see the polyfill for the implementation as well.

URL : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind