【问题标题】:Node js object exports节点 js 对象导出
【发布时间】:2016-11-12 00:47:51
【问题描述】:

有一个非常简单的问题,我找不到关于从 Node js 中的模块导出对象的答案,更具体地说,是访问对象属性。

这是我导出的对象:

exports.caravan = {
    month: "july"
};

这是我的主要模块:

var caravan = require("./caravan")

console.log(caravan.month);
console.log(caravan.caravan.month);

为什么我不能直接用caravan.month访问属性,而必须写caravan.caravan.month?

【问题讨论】:

  • “如果 caravan 是一个函数,我可以简单地用 caravan() 调用它”——不,你不能。
  • @Juhana 你说得对,我不能,应该是 caravan.caravan()。

标签: javascript node.js node-modules


【解决方案1】:

如果要获取对象,请使用

module.exports = {
  caravan = {
       month: "july"
  }
};

然后像这样得到它:

var caravan = require("./caravan")

您也可以查看:

console.log(caravan.caravan.month);

【讨论】:

    【解决方案2】:

    考虑使用require,您可以访问模块的module.exports 对象(别名为exports,但使用exports 有一些微妙之处,这使得使用module.exports 成为更好的选择)。

    获取您的代码:

    exports.caravan = { month: "july" };
    

    与此类似:

    module.exports.caravan = { month: "july" };
    

    与此类似:

    module.exports = {
      caravan : { month: "july" }
    };
    

    如果我们同样“翻译”require,将其替换为module.exports 的内容,您的代码将变为:

    var caravan = {
      caravan : { month: "july" }
    };
    

    这解释了为什么需要使用caravan.caravan.month

    如果你想删除额外的间接级别,你可以在你的模块中使用它:

    module.exports = {
      month: "july"
    };
    

    【讨论】:

      【解决方案3】:

      如果你想通过caravan.month 获取,那么:

      module.exports = {
          month: "july"
      };
      

      【讨论】:

      • 试试module.exports = { /* ... */ }
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多