module.exports和exports

module.exportsexports

本質上,exportsmodule.exports對象的引用ui

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是一個對象,而ba的引用(ab指向同一塊內存),因此輸出相同code

  • b修改原對象後,由於ab指向同一塊內存,因此修改會體如今a對象

  • b被覆蓋時,b指向了一塊新的內存;而a的指向不變,因此輸出不一樣內存

module.exportsexports的區別

  • module.exports的初始值是一個空對象{}console

  • exportsmodule.exports對象的一個引用class

  • require()返回值的是module.exports對象,而非exportsrequire

重置module.exportsexports,指向一個新對象時,會斷開兩者間的引用關係變量

使用方式

  • 如下兩種寫法相同,module.exports指向一個新對象,斷開兩者間的聯繫module

  • 再使用exports = module.exports使exports指向新對象,恢復兩者間的聯繫引用

    exports = module.exports = {...};
    
    /*
     * module.exports = {...};
     * exports = module.exports;
     */
相關文章
相關標籤/搜索