0

When I enter code console.log(this); in Chrome dev tools, it displays:

Window {stop: function, open: function, alert: function, confirm: function, prompt: function…}

but when I execute same code in node.js (v6.11.1) it displays:

{}

Shouldn't it display information about global object?

(Said code is only thing that is executed, it is not part of a program.)

igobivo
  • 433
  • 1
  • 4
  • 17
  • Those are all window/browser methods. Why would you expect the global environment for a node module to look like that? – Andy Aug 15 '17 at 13:52
  • I was unaware of the fact that this code would be implicitly encapsulated in a 'module'. Thanks. – igobivo Aug 15 '17 at 14:30

1 Answers1

1

In the top-level code in a Node module, this is equivalent to module.exports. That's the empty object you see. For example:

module.exports.a = 'test';
console.log(this); // 'test'

In browsers, without using "use strict"-directive, this refers to global object (Window).

Ivan Minakov
  • 1,432
  • 7
  • 12
  • Thanks, I get it now. Also this questions is spot on: https://stackoverflow.com/questions/15406062/in-what-scope-are-module-variables-stored-in-node-js – igobivo Aug 15 '17 at 14:28