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

评论

暂无评论