模块变量存储在 node.js 中的范围是什么?

编程入门 行业动态 更新时间:2024-10-27 17:21:59
本文介绍了模块变量存储在 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.js 或 require('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 中的范围是什么?

本文发布于:2023-05-27 09:59:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/285812.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   模块   js   node

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!