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

Ray*_*oal 2 javascript console this node.js

从节点REPL:

$ node
> var x = 50
> console.log(x)
50
> console.log(this.x)
50
> console.log(this === global)
true
Run Code Online (Sandbox Code Playgroud)

一切都有道理.但是,当我有一个脚本时:

$ 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
Run Code Online (Sandbox Code Playgroud)

不是我的预期.

我真的不有问题与REPL从脚本行为不同,但到底在哪节点文档中没有说类似"注意:当你运行一个脚本,值this设置global,而是___________ ".有谁知道,this当作为脚本运行时,在全局上下文中指的是什么?谷歌搜索"nodejs这个全局上下文脚本"带我到这个看起来非常有前途的页面,因为它描述了运行脚本的上下文,但它似乎没有提到在this任何地方使用表达式.我错过了什么?

the*_*eye 5

在Node.js中,截至目前,您创建的每个文件都称为模块.所以,当你在一个文件中运行程序时,this会参考module.exports.你可以这样检查一下

console.log(this === module.exports);
// true
Run Code Online (Sandbox Code Playgroud)

事实上,exports只是一个参考module.exports,所以以下也将打印true

console.log(this === exports);
// true
Run Code Online (Sandbox Code Playgroud)

可能相关:为什么在文件中和函数内声明'this'指向不同的对象