3

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 ?

1

1 Answer 1

13

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

Sign up to request clarification or add additional context in comments.

2 Comments

Note, if you run without a module it does print contents of global. Example: node -e 'console.log(this)'.
@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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.