node.js中的導(dǎo)入導(dǎo)出
定義
exports
——導(dǎo)出
module.exports
——導(dǎo)出
require
——導(dǎo)入
概念:
require
導(dǎo)入的是module.exports
的值,或是基本類(lèi)型,或是引用類(lèi)型,默認(rèn)module.exports
是一個(gè)空對(duì)象{}
,而exports
只是module.exports
的默認(rèn)空對(duì)象{}
的引用(地址)而已
這句話一定要理解,后面解釋都是按上面這條概念解釋的而已
分別給module.exports
和exports
的默認(rèn)值指向的對(duì)象{}
添加屬性
// index.js
module.exports.name = '我是默認(rèn)對(duì)象下的name屬性'
exports.name1 = "我是exports引用的對(duì)象下的name1屬性"
var ind = require('./index.js')
console.log(module.exports);
// { name: '我是默認(rèn)對(duì)象下的name屬性', name1: '我是exports引用的對(duì)象下的name1屬性' }
console.log(exports);
// { name: '我是默認(rèn)對(duì)象下的name屬性', name1: '我是exports引用的對(duì)象下的name1屬性' }
console.log(ind);
// { name: '我是默認(rèn)對(duì)象下的name屬性', name1: '我是exports引用的對(duì)象下的name1屬性' }
結(jié)果:很明顯,module.exports
和exports
默認(rèn)值指向的就是同一個(gè)對(duì)象的地址
好,稍作修改,我們?cè)?code>module.exports和exports
添加屬性后,把module.exports
的值指向一個(gè)新的對(duì)象,看看會(huì)發(fā)生什么
module.exports.name = '我是默認(rèn)對(duì)象下的name屬性'
exports.name1 = "我是exports引用的對(duì)象下的name1屬性"
module.exports = {
newName:'我是新賦值的對(duì)象下的newName屬性'
}
var ind = require('./index.js')
console.log(module.exports);
// { newName: '我是新賦值的對(duì)象下的newName屬性' }
console.log(exports);
// { name: '我是默認(rèn)對(duì)象下的name屬性', name1: '我是exports引用的對(duì)象下的name1屬性' }
console.log(ind);
// { newName: '我是新賦值的對(duì)象下的newName屬性' }
module.exports
指向被我們改了
exports
指向我們沒(méi)改,保持正常
require
導(dǎo)出的內(nèi)容變了
說(shuō)明:導(dǎo)出的是module.exports
,而不是exports
,module.exports
和exports
本身是不同的屬性