简体   繁体   中英

javascript define a constant global

In my project I encode some information in an array. The number 0 represent one thing and the number 134 another and so on. a few different modules use thees numbers. To help with readability I define some of them at the head of the modules but this will be super annoying to change in the future.

I want to have something like that:

 - constants -

   module.exports = function(){
      global var Bulding = 0;
      global var Tree = 1;
      ...}

 - some module -

 require('./constants')();
 <some code...>      
 if(arr[i] == Tree){
    <do things>
 }

Is this possible? or even better is there a javascript/nodejs way of doing this?

You should export that as a normal object with properties:

module.exports = {
    building: 0,
    tree: 1,
    ...
};

// Elsewhere:

var constants = require('./constants');
constants.tree;

For added protection, you can use Object.freeze() to prevent the constants from being changed.

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