简体   繁体   English

Node.js-具有相互依赖变量的Globals配置文件

[英]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. 我有一个globals.js文件,需要在我的应用程序中的多个文件之间进行访问。

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. 这个想法是,如果我更改canvas.width属性,所有更改都将降级。

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. 您可能正在寻找JavaScript的get语法 ,它使您可以将计算值当作属性来访问。 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. 但是,如果您确实想避免显式的函数调用,请使用getter。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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