Javascript 当作为脚本运行时,Node.js中“this”的上下文是什么?

Javascript 当作为脚本运行时,Node.js中“this”的上下文是什么?,javascript,node.js,console,this,Javascript,Node.js,Console,This,从节点REPL: $ node > var x = 50 > console.log(x) 50 > console.log(this.x) 50 > console.log(this === global) true 一切都有道理。但是,当我有脚本时: $ cat test_this.js var x = 50; console.log(x); console.log(this.x); console.log(this === global); $ node tes

从节点REPL:

$ node
> var x = 50
> console.log(x)
50
> console.log(this.x)
50
> console.log(this === global)
true
一切都有道理。但是,当我有脚本时:

$ cat test_this.js 
var x = 50;
console.log(x);
console.log(this.x);
console.log(this === global);
$ node test_this.js 
50
undefined
false
不是我所期望的


我对REPL的行为与脚本的不同并没有什么问题,但在节点文档中,它到底在哪里说了类似“注意:当运行脚本时,
this
的值并没有设置为
global
,而是设置为uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu,当作为脚本运行时,此在全局上下文中指的是什么?谷歌搜索“nodejsthisglobalcontextscript”让我看到了它看起来非常有希望,因为它描述了运行脚本的上下文,但它似乎没有提到在任何地方使用
这个
表达式。我遗漏了什么?

在Node.js中,到目前为止,您创建的每个文件都称为模块。因此,当您在文件中运行程序时,
这将引用
模块.exports
。你可以这样检查

console.log(this === module.exports);
// true
事实上,
exports
只是对
模块的引用。exports
,因此下面也将打印
true

console.log(this === exports);
// true

可能相关:

短语“…此项的初始值”表示您认为它将在以后发生变化。不可能。该值是在输入执行上下文时设置的,以后不能修改。问题似乎是“为什么
这个
在一个模块中不是全局对象?”。FWIW我找到了我问题的答案@RobG当然你是对的,我已经编辑了这个问题。(另外,我实际上并没有真正意识到运行一个简单的脚本确实是一个模块,尽管回想起来,我本应该这样做的,这样我就可以更容易地在谷歌上搜索答案,或者知道答案是
exports
。)。