0

I had read the following definition of "this" feature in JS: This is the object that the function is a property of. Based on this when I look at the example below, I expect the "this" to refer to the module object. However, this is not the case and the this had to be bound manually to the module object.

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

const unboundGetX = module.getX;
console.log(unboundGetX()); // The function gets invoked at the global scope
// expected output: undefined

const boundGetX = unboundGetX.bind(module);
console.log(boundGetX());
// expected output: 42
  • `unboundGetX` is not *a property of* anything anymore… – deceze Mar 29 '21 at 06:40
  • In JS, you can't just determine what does a function belong to. In this example, both `module.getX`, which is a property and `unboundGetX`, which is a variable, refer to the function. If you access it through the former way, `this` will be set to `module`, but if you access it through the latter way, `this` won't be set (will be set to the global object in non-strict mode). – FZs Mar 29 '21 at 06:41

0 Answers0