在node中犀勒,一個js模塊其實是一個對象耙册,可以通過console.log(module)打印出模塊對象胸私,如下:
Module {
? ? ? id: '.',
? ? ? exports: {},
? ? ? parent: null,
? ? ? filename: 'C:\\Users\...',
? ? ? loaded: false,
? ? ? children: [],
? ? ? paths: [
? ? ? ? ? ? 'C:\\User\\Administrator\...',
? ? ? ? ? ? 'C:\\node_modules\...'
? ? ? ]
}
其他js文件通過require()方法引用的時候酿傍,獲取的其實就是exports屬性弛秋,為了方便使用线召,node在每個模塊中引入了exports變量铺韧,其實相當于在每個模塊開頭加入:
var exports = module.exports;
也就是說exports是對module.exports的一個引用,如果模塊暴露過程中不直接對exports賦值灶搜,兩者是等價的祟蚀,例如:
//mod.js
exports.str = "string"; ? ?// 直接用exports暴露str參數(shù)
module.exports.str = "string"; ? ?//通過module.exports暴露str參數(shù)
//ext.js
var mod = require("./mod"); ? ?// 通過require引入mod.js模塊
console.log(mod); // { str: "string" }
如果直接賦值給exports,相當于切斷了兩者的聯(lián)系割卖,其他js文件引用到的是module.exports屬性的值前酿,例如:
//mod.js
exports = "string from exports"; ? ?// 直接用exports暴露str參數(shù)
module.exports = "string from module.exports"; ? ?//通過module.exports暴露str參數(shù)
//ext.js
var mod = require("./mod"); ? ?// 通過require引入mod.js模塊
console.log(mod); // "string from module.exports"