节点js对象导出 [英] Node js object exports

查看:70
本文介绍了节点js对象导出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Got a pretty simple question to which I cant find an answer regarding exporting a object form a module in Node js, more specifically accessing the objects properties.

这是我输出的对象:

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

这是我的主要模块:

var caravan = require("./caravan")

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

为什么我不能直接使用caravan.month访问这些属性但是必须写caravan.caravan.month?

Why cant I access the properties directly with caravan.month but have to write caravan.caravan.month?

推荐答案

考虑到 require ,您可以访问 module.exports 模块的对象(别名为 exports ,但使用出口使用 module.exports 更好的选择。)

Consider that with require, you gain access to the module.exports object of a module (which is aliased to exports, but there are some subtleties to using exports that make using module.exports a better choice).

带你的代码:

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

与此类似:

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

与此类似:

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

如果我们同样翻译 require ,用 module.exports 的内容替换它,你的代码就变成了这样:

If we similarly "translate" the require, by substituting it with the contents of module.exports, your code becomes this:

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

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

Which explains why you need to use caravan.caravan.month.

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

If you want to remove the extra level of indirection, you can use this in your module:

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

这篇关于节点js对象导出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆