简体   繁体   English

如何从函数 Javascript 内部定义全局常量?

[英]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:如果您确实想:

  • Have an initialised, but empty MODULES array during the time that bootstrap() is not yet called, and在尚未调用bootstrap()期间有一个已初始化但为空的MODULES数组,并且
  • Make MODULES immutable once it has been populated, and使MODULES填充后不可变,并且
  • Keep the current function signature of 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM