有一个非常简单的问题,我无法找到有关从 Node js 中的模块导出对象的答案,更具体地说是访问对象属性。
这是我导出的对象:
exports.caravan = {
month: "july"
};
这是我的主要模块:
var caravan = require("./caravan")
console.log(caravan.month);
console.log(caravan.caravan.month);
为什么我不能直接使用 caravan.month 访问属性,而必须编写 caravan.caravan.month?
最佳答案
考虑使用 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"
};
关于javascript - Node js 对象导出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38283777/