0

Let's have a look to this very basic program.js:

console.log(this);

Here is the output:

$ nodejs program.js 
{}

Now, if i do the samething in the repl console:

$ nodejs 
> console.log(this)

I see a log of things at undefined at the end.

Why do we not get the same result ?

Thanks

Bob5421
  • 6,002
  • 10
  • 44
  • 120
  • I am not sure how you are getting an empty object or undefined outside of a defined object this will refer to the global object. IE. this === global – thomasmeadows Aug 31 '17 at 19:32

1 Answers1

1

You are experiencing two different behaviors because you're basically executing code in two different environments.

In program.js, this answer applies. You're in a node.js module, so this is the same as module.exports.

In the node.js repl, this answer applies. You're not in a node.js module; you're in the repl which uses the global context. this is the same as global. If you executed the same code in-browser, it'd reference the window object instead of global.

Steven Goodman
  • 566
  • 3
  • 15