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

    你可能感兴趣的文章
    Pytest框架 之【用例执行顺序】
    查看>>
    Pytest框架中的测试用例执行方式!
    查看>>
    pytest框架快速入门-pytest运行时参数说明,pytest详解,pytest.ini详解
    查看>>
    Pytest框架环境切换实战教程!赶快收藏
    查看>>
    Pytest测试实战|Conftest.py详解
    查看>>
    Pytest测试框架快速搭建
    查看>>
    pytest测试框架:最强大的自动化测试工具,让测试变得轻松有趣
    查看>>
    pytest简介及jenkins集成
    查看>>
    Pytest自动化框架运行全局配置文件pytest.ini
    查看>>
    pytest自动化测试-Git中的测试用例运行
    查看>>
    Pytest自动化测试-简易入门教程(01)
    查看>>
    Pytest自动化测试-简易入门教程(02)
    查看>>
    Pytest自动化测试-简易入门教程(03)
    查看>>
    Pytest自动化测试指定执行测试用例
    查看>>
    Pytest自动化测试框架 fixture 传参实战
    查看>>
    pytest自动化测试框架pytest.ini配置文件详细
    查看>>
    Pytest自动化测试框架介绍
    查看>>
    Pytest自动化测试框架,建议收藏。
    查看>>
    Pytest自动化测试框架:mark用法---测试用例分组执行
    查看>>
    PyTorch 1.0 中文官方教程:强化学习 (DQN) 教程
    查看>>