为什么节点全局上下文===“this”有时仅在样本中?

我有以下test.js文件发出两行输出,每行testing严格相等的全局对象和this

 var c = require("console"); console.log(this === global); (function () { console.log(this === global); })(); 

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


真正

但是,当我从节点REPL中加载test.js时,它提供了不同的输出:

真正
真正

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

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

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

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

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

由于REPL的本质/目的,将REPL视为节点模块是没有意义的,所以REPL中的所有代码都只是在相同的范围内执行。