NodeJs定义全局常量
NodeJs define global constants
我想知道如何在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
相关文章:
- 全局变量和全局对象的属性之间有什么区别吗
- 正在全局范围中查找JavaScript函数
- delete关键字在全局变量上的不同行为
- 在javascript函数中设置全局变量
- 如何将getJson的响应保存在全局变量中
- 全局对象是属于哪个类的对象
- Javascript全局onclick监听器
- 从Javascript方法返回全局变量
- 访问jsrender模板中的全局javascript变量并更新它
- Javascript-在哪里放置常量,全局或本地
- 我可以在不注入控制器的情况下在 Angular 中使用全局常量吗?
- Meteor:全局常量未从app/lib/_constants.js中获取
- 如何循环遍历常量的全局命名空间?
- 在AngularJS中创建和访问全局常量
- Javascript / jQuery中的Access Rails全局常量
- 为什么我不应该在JavaScript中为常量使用全局变量呢?
- NodeJs定义全局常量
- PHP在PHP中设置全局常量中的硬编码URL
- 用javascript es6编写全局常量的正确方法是什么
- 如何在Angularjs中创建这个全局常量,以便在控制器之间共享