The JavaScript bind method haunts me

I have searched many articles on bind method, but i am still confused about it. Can someone provide me explanation or link to good article about bind method ?

Instead of just repeating your google efforts, maybe we’d be able to help you better if you discuss what you do and don’t understand about the bind method.

x = 9;
var module = {
    x: 81,
    getX: function () {
        return this.x;
    }
};

module.getX(); // 81

var getX = module.getX;
getX(); // 9, because in this case, "this" refers to the global object

// create a new function with 'this' bound to module
var boundGetX = getX.bind(module);
boundGetX(); // 81

references:

2 Likes

Initially, can you please tell me what is bind and what is it used for ?

@Manav_PNH_Infy

It has to do with context. Take a look at the example above,

calling

returns 81 but calling

returns 9 because getX() now refers to the variable x outside of module function constructor, which is the window object. You lost access to this inside of module because the reference changed.

Now if you want getX to refer x inside of module again, you have to bind the getX function to module constructor.

Hopefully this helps…

1 Like