博客
关于我
module.exports和exports
阅读量:127 次
发布时间:2019-02-26

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

在Node.js中,模块化编程中的变量导出是通过module.exports和exports来实现的。这两个关键字看似相似,但实际上有细微的差别。理解这些差别对于写出高效且可维护的代码至关重要。

模块化编程中的变量导出

模块在Node.js中可以通过module.exports来导出变量、函数或对象供其他模块使用。module.exports实际上是模块的主要导出接口,用于向外暴露模块的功能和数据。

exports的作用

exports并非一个直接的导出接口,而是一个指向module.exports的引用。初始时,exports和module.exports指向同一个对象。当对exports进行赋值时,实际上是修改了module.exports所指向的对象。例如:

exports = {  name: 'Alice'}

这会导致module.exports也变成 { name: 'Alice' }。因此,修改exports会影响module.exports。

module.exports的作用

相比之下,module.exports是一个可控的接口,可以通过它重新导出变量或对象。例如:

module.exports = {  name: 'Alice'}

此时,exports仍然指向原来的对象,而module.exports被重新赋值为新的对象。这种行为允许开发者在不影响其他模块的情况下,重新导出变量或对象。

示例比较

  • 修改module.exports后,exports变化
  • module.exports.name = 123;console.log(exports); // { name: 123 }console.log('------------------');console.log(module); // { id: '.', exports: { name: 123 }, ... }
    1. 重新赋值module.exports,不影响exports
    2. exports.name = 123;module.exports = { name: 234 };console.log(exports); // { name: 123 }console.log('------------------');console.log(module); // { id: '.', exports: { name: 234 }, ... }

      总结

      理解这两者的区别对编写模块化代码至关重要。exports和module.exports在某些情况下会共享同一个对象,而在其他情况下则不会。使用module.exports重新导出变量是更安全和可控的选择,尤其是当需要重新导出对象时。

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

    你可能感兴趣的文章
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    查看>>
    NO 157 去掉禅道访问地址中的zentao
    查看>>
    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 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 such file or directory AndroidManifest.xml
    查看>>