2

I have the following test.js file that emits two lines of output, each line tests for strict equality between the global object and this.

var c = require("console");

console.log(this === global);

(function () {
    console.log(this === global);
})();

When I run this file from the command line using node.exe test.js I get the following output:

false
true

However when I load test.js from inside the node REPL it provides me different output:

true
true

This is the full transcript of loading the script in the REPL

PS C:\Programming> node
> .load test.js
.load test.js
> var c = require("console");
undefined
> console.log(this === global);
true
undefined
>
> (function () {
...     console.log(this === global);
... })();
true
undefined
>
> .exit

What is the cause of difference in output between these two run scenarios of the same script?

Strict mode is not enabled in either case (node command line sets strict to false by default); the code doesn't invoke strict mode with 'use strict';.

I'm using node 5.9.0 on Windows 10 x64.

John K
  • 28,441
  • 31
  • 139
  • 229

1 Answers1

2

The reason is that the two environments are different. When you execute a file on the command line or require() a file, they are loaded as node modules which are executed in a special environment where this === module.exports (although you should use exports/module.exports instead of this in modules).

There is no sense in treating a REPL like a node module due to the nature/purpose of a REPL, so all of the code in the REPL is simply executed within the same scope.

mscdex
  • 104,356
  • 15
  • 192
  • 153