exports 和 module.exports 的区别

require 用来加载代码,而 exports 和 module.exports 则用来导出代码。但不少新手可能会迷惑于 exports 和 module.exports 的区别,为了更好的理解 exports 和 module.exports 的关系,咱们先来巩固下 js 的基础。示例:node

test.jsui

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

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

b.name = 2; console.log(a); console.log(b);对象

var b = {name: 3}; console.log(a); console.log(b);blog

运行 test.js 结果为:内存

{ name: 1 } { name: 1 } { name: 2 } { name: 2 } { name: 2 } { name: 3 }文档

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

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

  1. module.exports 初始值为一个空对象 {}
  2. exports 是指向的 module.exports 的引用
  3. require() 返回的是 module.exports 而不是 exports

如今咱们来看 Node.js 官方文档的截图: 屏幕快照 2016-09-29 上午11.59.44.png 咱们常常看到这样的写法:

exports = module.exports = somethings

上面的代码等价于:

module.exports = somethings exports = module.exports

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

转载自https://cnodejs.org/topic/5231a630101e574521e45ef8

         https://cnodejs.org/topic/52308842101e574521c16e06

相关文章
相关标签/搜索