为什么在定义导出属性之前调用module.exports时仍然有效

Why does module.exports still work when called before defining exported properties?

本文关键字:exports module 有效 调用 定义 属性 为什么      更新时间:2023-09-26

我有这个代码:

var config = module.exports = {};
config.foo = {...};

这个作品找到了,但我想知道为什么。

我觉得我可以考虑下面的实现,因为导出配置似乎更有意义,而不是将配置设置为module.exports.

var config = {};
config.foo = {...};
module.exports = config;

有人能解释一下吗?

var config = module.exports = {}; 

相当于

var config = (module.exports = {}); 

module.exports = {};
var config = module.exports;

此处导出的值为{}。因为configmodule.exports只是对同一对象{}的引用,所以属性foo仍然可以通过变量module.exportsconfig添加到该对象。