module.exports
和exports
本质上,
exports
是module.exports
对象的引用ui
var a = {x: "2"}; var b = a; console.log(a); // { x: '2' } console.log(b); // { x: '2' } b.x = 3; console.log(a); // { x: 3 } console.log(b); // { x: 3 } b = {x: 1}; console.log(a); // { x: 3 } console.log(b); // { x: 1 } console.log(module.exports === exports); // true
变量a
是一个对象,而b
是a
的引用(a
、b
指向同一块内存),因此输出相同code
b
修改原对象后,由于a
、b
指向同一块内存,因此修改会体如今a
上对象
当b
被覆盖时,b
指向了一块新的内存;而a
的指向不变,因此输出不一样内存
module.exports
和exports
的区别module.exports
的初始值是一个空对象{}
console
exports
是module.exports
对象的一个引用class
require()
返回值的是module.exports
对象,而非exports
require
重置
module.exports
或exports
,指向一个新对象时,会断开两者间的引用关系变量
如下两种写法相同,module.exports
指向一个新对象,断开两者间的联系module
再使用exports = module.exports
使exports
指向新对象,恢复两者间的联系引用
exports = module.exports = {...}; /* * module.exports = {...}; * exports = module.exports; */