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; */