当我在 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 中的范围是什么?
发布评论