NodeJs定义全局常量

即时通讯想知道如何在节点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