【问题标题】:How does exports object reference module.exports in Node.js?Node.js 中的导出对象如何引用 module.exports?
【发布时间】:2020-03-31 17:55:07
【问题描述】:

在 Node.js 中,模块对象包含一个导出属性,即一个空对象。此对象可用于引用 module.exports (exports.a = "A";),除非它被重新分配 (module.exports = "one";)。

我的问题是 - 是什么让这个导出对象引用 module.exports?

【问题讨论】:

标签: node.js module.exports


【解决方案1】:

CommonJS 模块实际上非常简单:您将所有代码放在一个文件中,然后将其包装在一个函数中。执行函数,执行后将module.exports的值返回给调用者。

你可以在node.js source code看到这个函数的头部:

const wrapper = [
  '(function (exports, require, module, __filename, __dirname) { ',
  '\n});'
];

包装器应用于require'd 文件中的代码,然后调用like this

  const exports = this.exports;
  const thisValue = exports;
  const module = this;
  if (requireDepth === 0) statCache = new Map();
  if (inspectorWrapper) {
    result = inspectorWrapper(compiledWrapper, thisValue, exports,
                              require, module, filename, dirname);
  } else {
    result = compiledWrapper.call(thisValue, exports, require, module,
                                  filename, dirname);
  }

如您所见,它非常简单。 const exports = this.exports,然后 exports 作为参数传递给包装函数 - 因此它们最初指向相同的值,但如果您重新分配其中任何一个,它们将不再这样做。

【讨论】:

  • 感谢您的快速回答!这很好地解释了这一点。
猜你喜欢
  • 1970-01-01
  • 2011-10-31
  • 1970-01-01
  • 1970-01-01
  • 2012-04-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多