Skip to content Skip to sidebar Skip to footer

Why Does Console.log(this) In Node Return An Empty Object?

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(t

Solution 1:

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


Post a Comment for "Why Does Console.log(this) In Node Return An Empty Object?"