nodejs module.exports与exports
参考简书,
https://www.jianshu.com/p/beafd9ac9656
https://segmentfault.com/a/1190000019399632
module.exports和exports一开始都是一个空对象{},实际上,这两个对象指向同一块内存。
这也就是说module.exports和exports是等价的(有个前提:不去改变它们指向的内存地址)。
例如:exports.age = 18和module.export.age = 18,这两种写法是一致的(都相当于给最初的空对象{}添加了一个属性,通过require得到的就是{age: 18})。
require引入的对象本质上是module.exports。这就产生了一个问题,当 module.exports和exports指向的不是同一块内存时,exports的内容就会失效。//people.js
module.exports = {name: '萤火虫叔叔'};
exports = {name: '萤火虫老阿姨'}
//main.js
let people = require('./people');
console.log(people);//输出:{name: '萤火虫叔叔'}
此时
module.exports指向了一块新的内存(该内存的内容为{name: '萤火虫叔叔'}),exports指向了另一块新的内存(该内存的内容为{name: '萤火虫老阿姨'})。require得到的是{name: '萤火虫叔叔'}。作者:萤火虫叔叔_WongYing
链接:https://www.jianshu.com/p/beafd9ac9656
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

浙公网安备 33010602011771号