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

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

问题描述

在此页面上( http://docs.nodejitsu.com/文章/ get-started / what-is-require ),它声明如果要将exports对象设置为函数或新对象,则必须使用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)),第一个是 [功能] 第二个是 { }

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

您能解释其背后的原因吗?我在这里阅读帖子: module.exports vs Node.js中的导出。它很有帮助,但没有解释它以这种方式设计的原因。如果直接退回出口参考会有问题吗?

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?

推荐答案

模块是一个普通的JavaScript对象,带有 exports 属性。 exports 是一个普通的JavaScript变量,恰好设置为 module.exports
在文件的末尾,node.js将基本上返回 module.exports require 功能。在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中的引用,这意味着如果将多个变量设置为同一个对象,则它们 所有相同的对象;那么 exports module.exports 是同一个对象。

但是如果你设置 exports 到新的东西,它将不再设置为 module.exports ,所以 exports module.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天全站免登陆