作为脚本运行时,Node.js中"this"的上下文是什么? [英] What is the context for `this` in Node.js when run as a script?

查看:39
本文介绍了作为脚本运行时,Node.js中"this"的上下文是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从节点REPL:

$ node
> var x = 50
> console.log(x)
50
> console.log(this.x)
50
> console.log(this === global)
true

一切都说得通.但是,当我有一个脚本时:

Everything makes sense. However, when I have a script:

$ 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的行为与脚本的行为并没有什么真正的问题,但是在Node文档的确切位置上,它写着注意:当您运行脚本时, this的值不是设置为 global ,而是___________."有谁知道,当以脚本运行时, this 在全局上下文中指的是什么?谷歌搜索"nodejs这个全局上下文脚本"将我带到此页面,它看起来很有希望,因为它描述了运行脚本的上下文,但似乎没有提到在任何地方使用 this 表达式.我想念什么?

I don't really have a problem with the REPL behaving differently from a script, but where exactly in the Node documentation does it say something like "NOTE: when you run a script, the value of this is not set to global, but rather to ___________." Does anyone know, what this refers to in the global context when run as a script? Googling "nodejs this global context script" takes me to this page which looks very promising, as it describes contexts for running scripts, but it doesn't seem to mention the use of the this expression anywhere. What am I missing?

推荐答案

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

In Node.js, as of now, every file you create is called a module. So, when you run the program in a file, this will refer the module.exports. You can check that like this

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

事实上, exports 只是对 module.exports 的引用,因此以下内容也会打印 true

As a matter of fact, exports is just a reference to module.exports, so the following will also print true

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

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

这篇关于作为脚本运行时,Node.js中"this"的上下文是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆