2

When I ran console.log(this) in node it returns empty object

console.log(this)             // return { }

But when I used IIFE in node

(function printThisObject(){
   console.log(this);         // return the global object
})();

Can someone explain this to me ?

DavidHyogo
  • 2,398
  • 3
  • 27
  • 41

1 Answers1

10

Because NodeJS runs your code in a module, and this references the object it creates for your module's exports (which is also the exports property on the module variable it provides you). (As they don't really mention that in the module documentation, I suspect using it is probably not a great idea — use exports instead.)

But your code calling the IIFE calls it with this referring to the global object, because in loose (non-strict) mode, calling a normal function not through an object property calls it with this set to the global object. (In strict mode, this would be undefined there.)

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
  • 3
    Note, if you run without a module it does print contents of `global`. Example: `node -e 'console.log(this)'`. – Dan Lowe Mar 06 '17 at 17:22
  • @DanLowe: Learn something new every day, I didn't realize immediate code was run at global scope, outside of a module. But you're right, it is (and thus `this` refers to the global object). – T.J. Crowder Mar 06 '17 at 17:24