问题
im wondering how to define global constants in node js.
My approach so far:
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
Ok thats fine so far. But then i wanted to structure my constants like this:
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
Hmm no MY_CONST is not constant any more... How can i solve this problem?
回答1:
You need to freeze inner object too. Something like that
module.exports = Object.freeze({
MY_TOPIC: Object.freeze({
MY_CONST: 'const one'
})
});
Demo
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);
回答2:
You can nest your freeze
calls, but I think what you actually want is
// 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
回答3:
Object values of the frozen object can be changed. Read the following example from the Object.freeze() doc to freeze all your object:
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
来源:https://stackoverflow.com/questions/39206115/nodejs-define-global-constants