exports和module.expors的关系和区别

我们在模块化开发中,必须会用到exports/module.exports这两个玩意导出变量或者函数。因为模块化开发中的每个模块都有自己的模块作用域。
比如:

//a.js
var foo = '苏小猫'
//b.js
console.log(foo)

我们在b.js中是没办法访问到a.js中的foo变量,所以b.js输出的是“undefine”。如果我们想在b.js模块中访问a.js中的foo变量,我们必须在a.js中用exports或者module.exports导出foo变量。
比如

//a.js
var foo = '苏小猫';

module.exports = foo;
//b.js
var foo = require('./b.js');

console.log(foo);

exportsmodule.expors的关系和区别?

在开发中,我们很纠结到底用exports还是module.exports,其实exports跟module.exports就是一个玩意,exports只是module.exports的一个引用。exports跟module.exports是等价的。我们可以在node里测试一下。

clipboard.png

每个模块最终返回的还是return module.exports;

在我们平常的理解中导出单个变量或者单个函数就用module.exports;

module.exports = function(){
    console.log("在你心里种点Bnum")
}

//我们require之后就会得到一个[Function]

导出多个变量就用exports;

exports.name = "苏小猫"
exports.tree = function(){
    console.log("在你心里种点Bnum")
}
//我们require之后就会得到一个对象{name:"苏小猫",tree:[Function]}

exports和module.exports本身就是一个空对象,exports.xxx就等于在一个对象里面添加东西。

为什么module.exports导出的是单个?

因为它本来是一个空对象,module.exports=xxx。现在你重新给它赋值了,所以它只导出这个xxx。

clipboard.png

如果给exports(exports={})重新赋值,这时它的意义就不同了;现在的exports,跟module.exports没有了半毛钱的关系了,exports.xxx = xxx;再往里面添加东西已经不会再影响最后返回回来的return module.exports了。

clipboard.png

看,现在age已经不进入最后的return module.exports里面了。

如果还想继续用exports.xxx,那就得重新再给module.exports赋值给exports。

clipboard.png

看,现在又生效了。

如果很纠结在开发中到底用很exports,还是module.exports,那就忘记exports吧(忘记它,我们不需要备胎,哈哈哈哈)。
一开始就是说了,exports本身就是module.exports的一个引用。exports能做的module.exports都能做。比如导出多个变量或者函数。

clipboard.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值