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

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

导出模块的两种方式

参考

  • exports
  • module.exports
// 定义方法,常量const myPI = 3.14const add = (a,b) => a + b;// 导出,两种方法任意都可以// 方法一:exports.myPI = myPIexports.add = add// 方法二:module.exports.myPI = myPImodule.exports.add = add// 方法二(变形)module.exports  = {       myPI,    add}

在阅读其它人的代码时,可能会遇到这两种不同的写法。所以我们还是有必要了解一下的。

cookie模块,body-parser模块,arry-flatten模块中的导出均采用不同的方式。

两个对象的关系

  • 初始exportsmodule.exports是指向同一块内存区域,其内容都是一个空对象。(exports是module.exports的别名)即:
exports === module.exports // 输出是 true

所以下面两种写法的效果是一样的:

//1 mymodule.js exports.f = function(){    } exports.pi = 3.1415926 //2 mymodule.js module.exports.f = function(){    } module.exports.pi = 3.1415926
  • 在定义模块时:
    如果直接给exports对象赋值(例如:exports={a:1,b:2}),此时,exports就不会再指向module.exports,而转而指向这个新对象,此时,exportsmodule.exports不是同一个对象。

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

图示

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

结论

在导出模块过程中,建议只用一种方式(建议直接使用module.exports)

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

你可能感兴趣的文章
no available service ‘default‘ found, please make sure registry config corre seata
查看>>
No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named 'pandads'
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>
No new migrations found. Your system is up-to-date.
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No qualifying bean of type ‘com.netflix.discovery.AbstractDiscoveryClientOptionalArgs<?>‘ available
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>
no session found for current thread
查看>>
No static resource favicon.ico.
查看>>
no such file or directory AndroidManifest.xml
查看>>