0

While I was testing what "this" was referring to at different phases in below code, I expected the last output to be the content of global, yet it showed {} instead.

var hero = {
  name: 'Monkey',
  sayMyName: function() {
    console.log(this.name);
  }
};

hero.sayMyName();   // A'Monkey'

var speakOut = hero.sayMyName;
speakOut();         // B global

const someone = { name: 'passenger' }

hero.sayMyName.call(someone);  // C'passenger'

function here() {
  console.log(this);
}

 const there = () => {
   console.log(this);
 }

here();   // D global
there();  // E global

output

monkey
undefined
passenger
<ref *1> Object [global] {
  global: [Circular *1],
  clearInterval: [Function: clearInterval],
  clearTimeout: [Function: clearTimeout],
  setInterval: [Function: setInterval],
  setTimeout: [Function: setTimeout] {
    [Symbol(nodejs.util.promisify.custom)]: [Getter]
  },
  queueMicrotask: [Function: queueMicrotask],
  clearImmediate: [Function: clearImmediate],
  setImmediate: [Function: setImmediate] {
    [Symbol(nodejs.util.promisify.custom)]: [Getter]
  }
}
{}

Does anyone know why?

Derek Yi
  • 37
  • 9
  • 1
    From the output, it's clear you're running this code in a Node.js CommonJS module in loose mode (not an ESM module, and not at global scope). B is `undefined` because, as you said, `this` during the call refers to the global object, which has no `name` property. D is the global object because you're calling the function in loose mode without setting `this` to anything in particular, so it gets set to the global object. E is the `module.exports` object for the module because that's what `this` is in a CommonJS Node.js module's top-level scope, and arrow functions close over `this`. – T.J. Crowder Dec 09 '21 at 10:05
  • 1
    This question really boils down to: "What is the value of `this` at the top-level scope of a CommonJS Node.js module?" To which the answer is: The `module.exports` object for the module (which is initially empty). If you put `console.log(this === module.exports);` in `example.js` and run it via `node example.js` (and you don't have a `package.json` with `"type": "module"` in it, which would make the module ESM instead of CommonJS), you'll see `true`. – T.J. Crowder Dec 09 '21 at 10:13
  • 1
    @T.J.Crowder thanks so much TJ! Glad to learn more about module.exports. – Derek Yi Dec 09 '21 at 10:49

0 Answers0