简体   繁体   中英

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. Is this possible?

Initialisation of MODULES has to happen inside bootstrap because of the config variable that I have to pass to registerModules .

If indeed you want to:

  • Have an initialised, but empty MODULES array during the time that bootstrap() is not yet called, and
  • Make MODULES immutable once it has been populated, and
  • Keep the current function signature of registerModules unchanged;

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:

const globals = {};

function bootstrap() {
  globals.MODULES = registerModules({...});
  Object.freeze(globals.MODULES);
}

Once you are happy with globals , you can also freeze that object:

Object.freeze(globals);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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