module.exports和exports
文章目录
module.exports和exports
本质上,
exports是module.exports对象的引用
JS引用
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指向同一块内存),所以输出相同b修改原对象后,因为a、b指向同一块内存,所以修改会体现在a上当
b被覆盖时,b指向了一块新的内存;而a的指向不变,所以输出不同
module.exports和exports的区别
module.exports的初始值是一个空对象{}exports是module.exports对象的一个引用require()返回值的是module.exports对象,而非exports
重置
module.exports或exports,指向一个新对象时,会断开二者间的引用关系
使用方式
以下两种写法相同,
module.exports指向一个新对象,断开二者间的联系-
再使用
exports = module.exports使exports指向新对象,恢复二者间的联系exports = module.exports = {...}; /* * module.exports = {...}; * exports = module.exports; */
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论