// 2.js
exports.id = 'exports的id';
exports.id2 = 'exports的id2';
exports.func = function(){
console.log('exports的函數(shù)');
};
exports.func2 = function() {
console.log('exports的函數(shù)2');
};
module.exports = {
id: 'module.exports的id',
func:function(){
console.log('module.exports的函數(shù)');
}
};
// 3.js
var a = require('./2.js');
// 當屬性和函數(shù)在module.exports都有定義時:
console.log(a.id); // module.exports的id
console.log(a.func()); // module.exports的函數(shù)
// 當屬性在module.exports沒有定義,函數(shù)在module.exports有定義
console.log(a.id2); // undefined
console.log(a.func()); // module.exports的函數(shù)
// 當函數(shù)在module.exports沒有定義,屬性在module.exports有定義
console.log(a.id); // module.exports的id
console.log(a.func2()); // 報錯了 TypeError: a.func2 is not a function
由上得知
1.module.exports像是exports的大哥,當module.exports以{}整體導(dǎo)出時會覆蓋exports的屬性和方法,
2.注意,若只是將屬性/方法掛載在module.exports./exports.上時,exports.id=1和module.exports.id=100,module.exports.id=function(){}和exports.id=function(){},最后id的值取決于exports.id和module.exports.id的順序,誰在后,就是最后的值