简体   繁体   中英

Node.js - Globals config file with inter-dependent variables

I have a globals.js file that needs to be accessible across multiple files in my app.

These globals are inter-dependent, and I would like to set up my data file so that the parameters are relative to one another. I am trying the following:

const config = {
  "canvas": {
    "width": 600,
  },
  "shape": {
    "width": function() {
      return config.canvas.width*0.9;
    };
  },
};

module.exports = config;

The idea is that if I change the canvas.width property, all changes will cascade down.

A big problem with this approach is that now I need to remember which global variables are functions. So for example in another file I would need to access it like this:

const config = require('./globals.js');
let width = config.shape.width();

Ideally I would like to access all globals as normal properties. To be clear, none of this needs to be dynamic (ie, recalculated at runtime) - once the app is running all these globals can be set in stone.

What's the best way to achieve this? Should I somehow "pre-compute" or "pre-build" the object?

You're likely looking for JavaScript's get syntax , which lets you access computed values as if they were properties. From your example, it's not obvious that this is absolutely necessary, since you could remember that you need to call a function. But if you really want to avoid explicit function calls, use a getter.

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