[英]NodeJS Global variable in Module
我有许多要根据要求加载的模块。 我需要一个限于该连接的全局变量,而不是整个代码库的全局范围。
这是来自主模块的一些示例代码。
var MainModule = function() {
// Do something fun
}
MainModule.prototype.Request = function() {
// Do more fun things
var Mod = require('./MyModule');
var MyModule = new Mod(this);
}
module.exports = MainModule;
。
var MyModule = function(MainModule) {
// Make MainModule Global ??
this.MainModule = MainModule;
}
MyModule.prototype.Foo = function() {
AnotherFunction('321312',function() {
// Need MainModule in this callback
}
}
module.exports = MyModule;
我希望MainModule中的this
在MyModule中是全局的,当然是另一个名称。 我发现处理此问题的唯一方法是创建this.MyModule
但这在每个模块上都很麻烦,而在有许多子模块的情况下,麻烦得多。
有没有一种干净的方法来处理在模块范围内可以为Global的变量?
那是你想做的吗?
MyModule.prototype.Foo = function() {
var that = this;
AnotherFunction('321312',function() {
that.MainModule;
}
}
如果我理解正确,那么您可以使用一个模块仅加载一次然后缓存的事实来创建一个变量,该变量将在应用程序的整个生命周期内存在,但对于该模块是私有的。 可以在导出之外的模块的顶级范围内定义它。 不过,在Foo中使用它之前,您仍然需要设置一次。
// modules are cached so its like a global to the module
var internalModuleGlobal;
var MyModule = function() {
}
MyModule.prototype.Foo = function() {
AnotherFunction('321312',function() {
if(!internalModuleGlobal) throw new Error("set internalModuleGlobal first!");
// Need MainModule in this callback
internalModuleGlobal.whatever; // accessible via closure
}
}
// call this once before Foo. doesn't have to be part of MyModule but is for e.
MyModule.prototype.setModuleOnce(mainModule) {
internalModuleGlobal = mainModule;
}
module.exports = MyModule;
我能够解决此问题的唯一方法是将引用传递到每个模块中。
var MyModule = function(MainModule) {
// Set it to pass it so all the methods
this.MainModule = MainModule;
}
MyModule.prototype.Foo = function() {
// Set it again to pass it through to any callbacks or sub functions
var MainModule = this.MainModule;
AnotherFunction('321312',function() {
MainModule.SomeMethod();
}
}
module.exports = MyModule;
因此,我在整个代码中加载的每个需要知道请求或用户信息的模块都必须通过该变量引用该变量。
我需要进行一些测试,以确保它一直正确地引用它,并且永远不要将其复制到新对象中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.