我的 module.exports = foo 返回一个空白对象 {}。谁能解释一下吗?
只有当我使用exports = module.exports = foo时,我的对象才不是空白。
最佳答案
module.exports
是定义导出时重要的变量。它是从 require('moduleName')
语句返回的实际对象。
为了方便起见, Node 基本上通过以下方式预定义了 exports
作为别名:
var exports = module.exports;
这样,您就可以分配给 module.exports
或仅分配给 exports
。因此,您可以执行其中任何一个操作,它们都会创建相同的结果,因为 module.exports === Exports
:
module.exports.myFunc1 = function() {};
module.exports.myFunc2 = function() {};
或者这个:
exports.myFunc1 = function() {};
exports.myFunc2 = function() {};
但是,当您通过为其分配新对象来重新定义 module.exports
时,exports
不再与 module.exports
相同的对象。
module.exports = {
myFunc1: function() {},
myFunc2: function() {}
};
现在,exports !== module.exports
,因为您为 module.exports
分配了一个新对象,并且 exports
仍然指向原始的 module.exports
。
因此,为了保留其原来的方式(如果模块中的任何其他代码引用 exports
,通常需要确保 exports
再次与 module.exports
相同,代码如下:
module.exports = exports = {
myFunc1: function() {},
myFunc2: function() {}
};
如果模块中的代码从不引用 exports
本身,那么您不需要以任何方式使用它,因为只有 module.exports
实际上对外界很重要。
关于node.js - 为什么exports = module.exports = {}; ?为什么不只是 module.exports 呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26560363/