NodeJs定义全局常量

NodeJs define global constants

本文关键字:常量 全局 定义 NodeJs      更新时间:2023-09-26

我想知道如何在node js中定义全局常量。

目前为止我的方法:

constants.js:

module.exports = Object.freeze({
MY_CONST: 'const one'});

controller.js:

var const = require(./common/constants/constants.js);
console.log(const.MY_CONST) ==> const one
const.MY_CONST ='something'
console.log(const.MY_CONST) ==> const one

好的,到目前为止还好。然后我想这样构造我的常量:

constants.js:

module.exports = Object.freeze({
    MY_TOPIC: {
        MY_CONST: 'const one'
    }
});

controller.js:

var const = require(./common/constants/constants.js);
console.log(const.MY_TOPIC.MY_CONST) ==> const one
const.MY_TOPIC.MY_CONST ='something'
console.log(const.MY_TOPIC.MY_CONST) ==> something

嗯不MY_CONST不再是常量了…我怎样才能解决这个问题?

也需要冻结内部对象。像这样的

module.exports = Object.freeze({
    MY_TOPIC: Object.freeze({
        MY_CONST: 'const one'
    })
});

var consts = Object.freeze({
  MY_TOPIC: Object.freeze({
    MY_CONST: 'const one'
  })
});
console.log(consts.MY_TOPIC.MY_CONST);
consts.MY_TOPIC.MY_CONST = "something";
console.log(consts.MY_TOPIC.MY_CONST);

你可以嵌套你的freeze调用,但我认为你真正想要的是

// constants.js
module.exports = Object.freeze({
    MY_CONST: 'const one'
});

// controller.js
const MY_TOPIC = require(./common/constants/constants.js);
console.log(MY_TOPIC.MY_CONST) // ==> const one
MY_TOPIC.MY_CONST = 'something'; // Error
console.log(MY_TOPIC.MY_CONST) // ==> const one

可以修改冻结对象的对象值。阅读以下Object.freeze()文档中的示例来冻结所有对象:

obj1 = {
  internal: {}
};
Object.freeze(obj1);
obj1.internal.a = 'aValue';
obj1.internal.a // 'aValue'
// To make obj fully immutable, freeze each object in obj.
// To do so, we use this function.
function deepFreeze(obj) {
  // Retrieve the property names defined on obj
  var propNames = Object.getOwnPropertyNames(obj);
  // Freeze properties before freezing self
  propNames.forEach(function(name) {
    var prop = obj[name];
    // Freeze prop if it is an object
    if (typeof prop == 'object' && prop !== null)
      deepFreeze(prop);
  });
  // Freeze self (no-op if already frozen)
  return Object.freeze(obj);
}
obj2 = {
  internal: {}
};
deepFreeze(obj2);
obj2.internal.a = 'anotherValue';
obj2.internal.a; // undefined