【问题标题】:NodeJs define global constantsNodeJs 定义全局常量
【发布时间】:2016-08-29 12:16:00
【问题描述】:

我想知道如何在节点 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 不再是常量... 我该如何解决这个问题?

【问题讨论】:

  • const 不是有效的变量名。

标签: javascript node.js constants


【解决方案1】:

您也需要冻结内部对象。类似的东西

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);

【讨论】:

    【解决方案2】:

    你可以嵌套你的 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
    

    【讨论】:

      【解决方案3】:

      可以更改冻结对象的对象值。 从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
      

      【讨论】:

      猜你喜欢
      • 2016-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多