“module.exports"之间的区别和“出口"在 CommonJs 模块系统中 [英] Difference between "module.exports" and "exports" in the CommonJs Module System

查看:34
本文介绍了“module.exports"之间的区别和“出口"在 CommonJs 模块系统中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此页面上 (http://docs.nodejitsu.com/articles/getting-started/what-is-require),它指出如果要将导出对象设置为函数或新的对象,你必须使用 module.exports 对象."

On this page (http://docs.nodejitsu.com/articles/getting-started/what-is-require), it states that "If you want to set the exports object to a function or a new object, you have to use the module.exports object."

我的问题是为什么.

// right
module.exports = function () {
  console.log("hello world")
}
// wrong
exports = function () {
  console.log("hello world")
}

我控制台记录了结果 (result=require(example.js)),第一个是 [Function] 第二个是 {}.

I console.logged the result (result=require(example.js)) and the first one is [Function] the second one is {}.

你能解释一下背后的原因吗?我在这里阅读了这篇文章:module.exports 与 Node.js 中的导出.这很有帮助,但没有解释为什么这样设计的原因.直接返回exports的reference会不会有问题?

Could you please explain the reason behind it? I read the post here: module.exports vs exports in Node.js . It is helpful, but does not explain the reason why it is designed in that way. Will there be a problem if the reference of exports be returned directly?

推荐答案

module 是一个带有 exports 属性的普通 JavaScript 对象.exports 是一个普通的 JavaScript 变量,恰好设置为 module.exports.在文件的末尾,node.js 基本上会返回"module.exportsrequire 函数.在 Node 中查看 JS 文件的一种简化方法可能是这样的:

module is a plain JavaScript object with an exports property. exports is a plain JavaScript variable that happens to be set to module.exports. At the end of your file, node.js will basically 'return' module.exports to the require function. A simplified way to view a JS file in Node could be this:

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

// your code

return module.exports;

如果你在 exports 上设置一个属性,比如 exports.a = 9;,那也会设置 module.exports.a因为对象在 JavaScript 中是作为引用传递的,这意味着如果你为同一个对象设置多个变量,它们都是同一个对象;所以 exportsmodule.exports 是同一个对象.
但是如果你将 exports 设置为新的东西,它将不再设置为 module.exports,所以 exportsmodule.exports 不再是同一个对象.

If you set a property on exports, like exports.a = 9;, that will set module.exports.a as well because objects are passed around as references in JavaScript, which means that if you set multiple variables to the same object, they are all the same object; so then exports and module.exports are the same object.
But if you set exports to something new, it will no longer be set to module.exports, so exports and module.exports are no longer the same object.

这篇关于“module.exports"之间的区别和“出口"在 CommonJs 模块系统中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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