exports and module.exports

结论:exports是module.exports的引用,初始化为:exports = module.exports = {},即exports和module.exports指向同一个对象。但是require函数执行后只返回module.exports。

为了验证上面的结论,我们来看下面两个例子:
eg1:

greet.js:
exports.greet = function () {
  console.log("hello node.");
};
console.log(exports);
console.log(module.exports);
app.js:
var Greet = require('./greet.js');
Greet.greet();

然后执行node app.js你会得到如下结果:

{ greet: [Function] }
{ greet: [Function] }
hello node.

因为exports和module.exports指向同一个对象,当通过exports修改这个对象后,module.exports指向的对象也会改变。

eg2:

greet.js:
module.exports = function() {
    console.log("hello node");
};
console.log(exports);
console.log(module.exports);
app.js:
var greet = require('./greet.js');
greet();

然后执行node app.js,结果如下:

{}
{ greet: [Function] }
hello node.

为什么会得到上面结果呢?greet.js中module.exports被重写,指向了一个函数。这就导致exports和module.exports分别指向不同的对象,而且require函数执行时module.exports被返回。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 描述 今天写react 的一个组件的时候,遇见一个问题,我想要exports defaults withroute...
    星期六1111阅读 3,414评论 0 2
  • Node.js是目前非常火热的技术,但是它的诞生经历却很奇特。 众所周知,在Netscape设计出JavaScri...
    w_zhuan阅读 9,012评论 2 41
  • 模块 Node 有简单的模块加载系统。在 Node 里,文件和模块是一一对应的。下面例子里,foo.js加载同一个...
    保川阅读 3,790评论 0 0
  • Node.js是目前非常火热的技术,但是它的诞生经历却很奇特。 众所周知,在Netscape设计出JavaScri...
    Myselfyan阅读 9,553评论 2 58
  • 2016年联考再次落下了帷幕,这是我第七年落榜。说起来挺丢脸的,从毕业那一年开始,我年年在公考大军里徘徊。头几年的...
    土豆爱番茄阅读 1,513评论 0 0

友情链接更多精彩内容