Souvik Ghosh
Souvik Ghosh

Reputation: 4606

Understanding bind() in JavaScript

As per MDN: The bind method

Calling f.bind(someObject) creates a new function with the same body and scope as f, but where this occurs in the original function, in the new function it is permanently bound to the first argument of bind, regardless of how the function is being used:

function f() {
  return this.a;
}

var g = f.bind({a: 'azerty'});
console.log(g()); // azerty

var h = g.bind({a: 'yoo'}); // bind only works once!
console.log(h()); // azerty

var o = {a: 37, f: f, g: g, h: h};
console.log(o.a, o.f(), o.g(), o.h()); // 37, 37, azerty, azerty

But when I try the code below:

var module = {
  x: 42,
  getX: function() {
    return this.x;
  }
}
    
var unboundGetX = module.getX;
console.log(unboundGetX()); // The function gets invoked at the global scope
// expected output: undefined
    
var boundGetX = unboundGetX.bind(module);
console.log(boundGetX()); // expected output: 42
 
module.x = 43;
boundGetY = boundGetX.bind(module);
console.log(boundGetY()); // shouldn't this be 42??

Expected output:

undefined
42
42

Actual output:

undefined
42
43

Can someone please explain this to me?

Upvotes: 1

Views: 235

Answers (3)

Siddharth Chauhan
Siddharth Chauhan

Reputation: 92

When you change the value of the same object then you are not binding another object so the value is changed.

  var module = {
      x: 42,
      getX: function() {
        return this.x;
      }
    }
    
    var unboundGetX = module.getX;
    console.log(unboundGetX()); // The function gets invoked at the global scope
    // expected output: undefined
    
    var boundGetX = unboundGetX.bind(module);
    console.log(boundGetX());  // expected output: 42
   
    var module2 = {
      x: 43,
      getX: function() {
        return this.x;
      }
    }
    boundGetY = boundGetX.bind(module);
    console.log(boundGetY());  

Upvotes: 0

SBD
SBD

Reputation: 146

here module is a constant, but module.x is not. that's the reason you can change module.x value but you can't change module.

so you are changing value of module, not module itself.

Upvotes: 3

dwjohnston
dwjohnston

Reputation: 11813

I'm not following what you are confused about - it looks like it is working as described.

  1. unboundGetX is a reference to your function.
  2. You change the value of module.x to 43
  3. You create a new method boundGetY by calling unboundGetX.bind(module) - ie, the this that boundGetY refers to is module.
  4. You call boundGetY() - it refers to this.x which is the value of the module.x, 43.

Upvotes: 0

Related Questions