Search code examples
javascriptecmascript-5ecma

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?


Solution

  • 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.