天天看点

nodejs 中 exports 和 module.exports 的关系

exports 与module.exports 是nodejs中用来导入导出模块的指令,但是连两者的关系比较复杂,这里简单总结一下
  • 每个模块都有一个module对象;
  • module对象中有一个exports对象;
  • 我们可以把对象需要把导出的成员挂载到module.exports接口对象中;
  • 也就是:

    module.exports.xxx = xxx

    的方式;
  • node在每一个模块中都提供了一个成员叫做:

    exports

    并且

    exports === module.exports

    结果是

    true

  • 所以对于

    module.exports.xxx = xxx

    可以简化为

    exports.xxx === xxx

  • 当一个模块需要导出单个成员的时候,必须使用

    module.exports === xxx

    的方式,不要使用

    exports === xxx

    ,因为每个模块最终向外

    return

    的是

    module.exports

    ,而

    exports

    只是一个引用;
  • 所以即使给

    exports = xx

    重新赋值,也不会影响

    module.exports

    ,除了很暴力的直接把

    exports = module.exports

    ,直接重新建立引用关系

继续阅读