exports 和 module.exports 的区别
@zs.duan
exports 和 module.exports 的区别
阅读量:944
2022-09-09 15:03:10

exports 和 module.exports 的区别

nswbmw Node前端 2020-04-11 20:26

今天来解决一个简单的问题,exports 和 module.exports 区别


require 用来加载代码,而 exports 和 module.exports 则用来导出代码。

但很多新手可能会迷惑于 exports 和 module.exports 的区别,为了更好的理解 exports 和 module.exports 的关系,我们先来巩固下 js 的基础。示例:

test.js

  1. var a = {name: 1}; var b = a;

  2.  

  3. console.log(a); console.log(b);

  4.  

  5. b.name = 2;

  6.  

  7. console.log(a); console.log(b);

  8.  

  9. var b = {name: 3};

  10.  

  11. console.log(a); console.log(b);

运行 test.js 结果为:

  1. { name: 1 } { name: 1 }

  2.  

  3. { name: 2 } { name: 2 }

  4.  

  5. { name: 2 } { name: 3 }

解释:a 是一个对象,b 是对 a 的引用,即 a 和 b 指向同一块内存,所以前两个输出一样。当对 b 作修改时,即 a 和 b 指向同一块内存地址的内容发生了改变,所以 a 也会体现出来,所以第三四个输出一样。当 b 被覆盖时,b 指向了一块新的内存,a 还是指向原来的内存,所以最后两个输出不一样。

明白了上述例子后,我们只需知道三点就知道 exports 和 module.exports 的区别了:

  1. module.exports 初始值为一个空对象 {}

  2. exports 是指向的 module.exports 的引用

  3. require() 返回的是 module.exports 而不是 exports

现在我们来看 Node.js 官方文档的截图:图片

我们经常看到这样的写法:

  1. exports = module.exports = somethings

上面的代码等价于:

  1. module.exports = somethings

  2. exports = module.exports

原理很简单,即 module.exports 指向新的对象时,exports 断开了与 module.exports 的引用,那么通过 exports = module.exports 让 exports 重新指向 module.exports 即可。

 

 

Web Worker 使用教程

进程与线程的一个简单解释

Nodejs内存限制与解决方案

深入理解react中的虚拟DOM、diff算法

 

评论:

还没有人评论 快来占位置吧