博客
关于我
node.js 导出模块的两种方式 exports module.exports
阅读量:254 次
发布时间:2019-03-01

本文共 885 字,大约阅读时间需要 2 分钟。

在模块化编程中,模块的导出方式有两种主要方法,分别是exportsmodule.exports。了解这两种方法的区别及其适用场景,对于理解模块导出机制具有重要意义。

exports与module.exports的关系

在初始阶段,exportsmodule.exports实际上是指向同一块内存区域,内容都是一个空对象。具体来说:

exports === module.exports // 输出是 true

这意味着在定义模块时,无论直接使用exports还是module.exports赋值,结果都是一样的。例如:

//1 mymodule.jsexports.f = function() {}exports.pi = 3.1415926//2 mymodule.jsmodule.exports.f = function() {}module.exports.pi = 3.1415926

两种写法的效果完全一致。

exports的特殊情况

需要注意的是,当直接将exports对象赋值时(例如:exports={a:1,b:2}),此时exports就不再指向module.exports,而是指向一个新对象。这种情况下,exportsmodule.exports就不再是同一个对象。

如何正确导出模块

在引入某模块时,应以该模块代码中module.exports指向的内容为准。例如:

// mymodule.jsmodule.exports = {  myPI: 3.14,  add: (a, b) => a + b}

这种方式是最常见且推荐的导出方式。

常见模块的导出方式

在实际开发中,许多模块采用不同的导出方式。例如:

  • cookie模块通常使用module.exports的形式导出。
  • body-parser模块同样采用module.exports的方式。
  • array-flatten模块也遵循这一规则。

结论

在导出模块时,建议只使用一种方式,并且建议直接使用module.exports。这不仅简化了代码,也符合大多数模块的标准导出方式。

转载地址:http://ddca.baihongyu.com/

你可能感兴趣的文章
ThreadLocal线程内部存储类
查看>>
thinkphp 常用SQL执行语句总结
查看>>
Oracle:ORA-00911: 无效字符
查看>>
Text-to-Image with Diffusion models的巅峰之作:深入解读 DALL·E 2
查看>>
TCP基本入门-简单认识一下什么是TCP
查看>>
tableviewcell 中使用autolayout自适应高度
查看>>
Orcale表被锁
查看>>
svn访问报错500
查看>>
org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned
查看>>
org.apache.ibatis.type.TypeException: Could not resolve type alias 'xxxx'异常
查看>>
org.apache.poi.hssf.util.Region
查看>>
org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
查看>>
org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /
查看>>
org.hibernate.HibernateException: Unable to get the default Bean Validation factory
查看>>
org.hibernate.ObjectNotFoundException: No row with the given identifier exists:
查看>>
SQL-CLR 类型映射 (LINQ to SQL)
查看>>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
查看>>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
查看>>
org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded
查看>>
org.tinygroup.serviceprocessor-服务处理器
查看>>