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

你可能感兴趣的文章
nginx+php的搭建
查看>>
Nginx+Redis+Ehcache:大型高并发与高可用的三层缓存架构总结
查看>>
nginx+tomcat+memcached
查看>>
nginx+tomcat单个域名及多个域名配置
查看>>
Nginx+Tomcat实现动静分离
查看>>
nginx+Tomcat性能监控
查看>>
nginx+uwsgi+django
查看>>
nginx+vsftp搭建图片服务器
查看>>
Nginx-http-flv-module流媒体服务器搭建+模拟推流+flv.js在前端html和Vue中播放HTTP-FLV视频流
查看>>
nginx-vts + prometheus 监控nginx
查看>>
Nginx/Apache反向代理
查看>>
Nginx: 413 – Request Entity Too Large Error and Solution
查看>>
nginx: [emerg] getpwnam(“www”) failed 错误处理方法
查看>>
nginx: [emerg] the “ssl“ parameter requires ngx_http_ssl_module in /usr/local/nginx/conf/nginx.conf:
查看>>
nginx: [error] open() “/usr/local/nginx/logs/nginx.pid“ failed (2: No such file or directory)
查看>>
nginx:Error ./configure: error: the HTTP rewrite module requires the PCRE library
查看>>
Nginx:objs/Makefile:432: recipe for target ‘objs/src/core/ngx_murmurhash.o‘解决方法
查看>>
nginxWebUI runCmd RCE漏洞复现
查看>>
nginx_rtmp
查看>>
Vue中向js中传递参数并在js中定义对象并转换参数
查看>>