模块变量存储在 node.js 中的范围是什么? [英] In what scope are module variables stored in node.js?

查看:31
本文介绍了模块变量存储在 node.js 中的范围是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在 node.js 模块中执行此操作时:

When I do this in my node.js module:

var abc = '123';

它去哪儿了?我的意思是:在浏览器中,它进入 window.abc(如果没有在函数中执行或以其他方式执行)

Where does it go? And by this I mean: in the browser it goes in window.abc (if not executed in a function or otherwise)

如果我执行这个:

abc = '123';

然后我可以在 global.abc 中找到它,但这不是我想要的.

Then I can find it in global.abc, but that's not how I want it.

推荐答案

与浏览器中的变量默认分配给全局空间(即窗口)不同,在 Node 中变量的范围限定为模块(文件)除非您明确将它们分配给 module.exports.

Unlike the browser, where variables are by default assigned to the global space (i.e. window), in Node variables are scoped to the module (the file) unless you explicitly assign them to module.exports.

实际上,当您运行 node myfile.jsrequire('somefile.js') 时,文件中的代码如下:

In fact, when you run node myfile.js or require('somefile.js') the code in your file is wrapped as follow:

(function (exports, require, module, __filename, __dirname) {
     // your code is here
});

这篇关于模块变量存储在 node.js 中的范围是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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