我想知道如何在节点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不再是常数...... 我该如何解决这个问题?
答案 0 :(得分:2)
你也需要冻结内部对象。像这样的东西
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);
&#13;
答案 1 :(得分:0)
您可以嵌套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
答案 2 :(得分:0)
可以更改冻结对象的对象值。
请阅读Object.freeze()
doc中的以下示例以冻结您的所有对象:
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