【发布时间】:2019-12-26 02:47:53
【问题描述】:
我试图避免在我的 server.js 文件中使用全局变量,但需要各种函数可访问和可写的变量。但是,我不确定范围是否与客户端的工作方式相同(因为它看起来更“隐藏”)。我在某处读到模块有自己的范围,但是如果我在那里放置变量并且它们可以在 server.js 中访问,那与全局范围不是一回事吗?例如:
//module.js
var config = [
{var1: 1},
{var2: 2},
{var3: 3}
]
module.exports = {
config
};
//server.js
const { config } = require("./config.js")
function function1() {
var a = config[0].var1
bar b = config[0].var2
config[0].var3 = a+b // changing var3 value in module
}
以这种方式使用模块是否可以接受?如果不是,这里会被认为是更好的做法吗?
谢谢
【问题讨论】:
-
以这种方式使用模块是否可以接受? 如果可行,则可以接受。现在你真正想做的事情还不清楚......关于范围,你的答案可能是:Last but not least, let's make this clear — module features are imported into the scope of a single script — they aren't available in the global scope.
标签: javascript node.js express