[英]How to a define a global constant from inside a function Javascript?
I am building an application composed of a set of modules that get loaded when the application bootstrap:我正在构建一个由一组模块组成的应用程序,这些模块在应用程序引导时加载:
const MODULES = []
function registerModules(config) {
return modules.map(module => (new module(config)).install());
}
function bootstrap() {
MODULES = registerModules({...});
}
The above of-course will raise an error.以上当然会引发错误。 What I want to do is to assign the
MODULE
constant only when the app start but then it should be fixed.我想要做的是仅在应用程序启动时分配
MODULE
常量,然后它应该被修复。 Is this possible?这可能吗?
Initialisation of MODULES
has to happen inside bootstrap
because of the config variable that I have to pass to registerModules
.由于我必须传递给
registerModules
的 config 变量,因此MODULES
初始化必须在bootstrap
内部进行。
If indeed you want to:如果您确实想:
MODULES
array during the time that bootstrap()
is not yet called, andbootstrap()
期间有一个已初始化但为空的MODULES
数组,并且MODULES
immutable once it has been populated, andMODULES
填充后不可变,并且registerModules
unchanged;registerModules
的当前函数签名不变; Then you could do it as follows:然后你可以这样做:
function bootstrap() {
Object.freeze(Object.assign(MODULES, registerModules({...})));
// OR:
// MODULES.push(...registerModules({...}));
// Object.freeze(MODULES);
}
If you don't insist on the existence of MODULES
before bootstrap()
is called, and you are open to store that information inside an object, then you could proceed as follows:如果您在调用
bootstrap()
之前不坚持MODULES
的存在,并且您愿意将该信息存储在一个对象中,那么您可以按以下步骤进行:
const globals = {};
function bootstrap() {
globals.MODULES = registerModules({...});
Object.freeze(globals.MODULES);
}
Once you are happy with globals
, you can also freeze that object:一旦您对
globals
感到满意,您还可以冻结该对象:
Object.freeze(globals);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.