gpt4 book ai didi

javascript - NodeJs 定义全局常量

转载 作者:行者123 更新时间:2023-11-29 21:16:32 24 4
gpt4 key购买 nike

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

到目前为止我的方法:

常量.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

好的,到目前为止还不错。但后来我想像这样构造我的常量:

常量.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);

关于javascript - NodeJs 定义全局常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39206115/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com