博客
关于我
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/

你可能感兴趣的文章
Stream API:filter、map和flatMap 的用法
查看>>
STM32工作笔记0032---编写跑马灯实验---寄存器版本
查看>>
ssm旅游信息管理系统的设计与实现bus56(程序+开题)
查看>>
order by rand()
查看>>
SSM(Spring+SpringMvc+Mybatis)整合开发笔记
查看>>
Orderer节点启动报错解决方案:Not bootstrapping because of 3 existing channels
查看>>
org.apache.axis2.AxisFault: org.apache.axis2.databinding.ADBException: Unexpected subelement profile
查看>>
sql查询中 查询字段数据类型 int 与 String 出现问题
查看>>
org.apache.commons.beanutils.BasicDynaBean cannot be cast to ...
查看>>
org.apache.dubbo.common.serialize.SerializationException: com.alibaba.fastjson2.JSONException: not s
查看>>
sqlserver学习笔记(三)—— 为数据库添加新的用户
查看>>
org.apache.http.conn.HttpHostConnectException: Connection to refused
查看>>
org.apache.ibatis.binding.BindingException: Invalid bound statement错误一例
查看>>
org.apache.ibatis.exceptions.PersistenceException:
查看>>
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
查看>>