Search code examples
javascriptfunctionscoping

Ridiculous scoping in Js


Can someone explain to me why the second function call returns undefined? I see no reason for that. The reference of the object method is stored in a variable, so it should be printed out. Why the result is undefined? The first function call is successful and the only difference is that the second one is stored in a variable.

const module = {
  x: 42,
  getX: function() {
    return this.x;
  }
};

//1 - returns 42
console.log(module.getX());

//2 - returns undefined
const unboundGetX = module.getX;
console.log(unboundGetX());


Solution

  • Because unboundGetX function is called by the global window variable, unboundGetX() it's like writing window.unboundGetX() so the this will refer to the global scope which is "window" object so it's also like you wrote return window.x which is logically "undefined".

    it will be better to bind your scope to the same object like this :

    const module = {
      x: 42,
      getX: function() {
        return this.x;
      }
    };
    
    console.log(module.getX());
    
    const unboundGetX = module.getX.bind(module); // we bind getX function to module scope instead of the global scope (which is the window variable)
    console.log(unboundGetX());