Javascript

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

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s