为什么节点全局上下文 === 'this' 只是有时在样本中?

Why does the node global context === 'this' only sometimes, in a sample?

我有以下 test.js 文件,它发出两行输出,每行测试全局对象和 this 之间的严格相等性。

var c = require("console");

console.log(this === global);

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

当我使用node.exe test.js从命令行运行这个文件时,我得到以下输出:

false
true

然而,当我从节点 REPL 内部加载 test.js 时,它为我提供了不同的输出:

true
true

这是在 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

同一脚本的这两个运行场景输出不同的原因是什么?

在这两种情况下都没有启用严格模式(节点命令行默认将strict设置为false);该代码不会使用 'use strict'; 调用严格模式。

我在 Windows 10 x64 上使用节点 5.9.0。

原因是两个环境不一样。当您在命令行上执行文件或 require() 文件时,它们将作为节点模块加载,这些模块在 this === module.exports 的特殊环境中执行(尽管您应该使用 exports/module.exports 而不是模块中的 this)。

由于 REPL 的 nature/purpose,将 REPL 视为节点模块是没有意义的,因此 REPL 中的所有代码都在同一范围内简单地执行。