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);
exports跟module.expors的关系和区别?
在开发中,我们很纠结到底用exports还是module.exports,其实exports跟module.exports就是一个玩意,exports只是module.exports的一个援用。exports跟module.exports是等价的。我们可以在node里测试一下。
每个模块终究返回的还是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。
以上就是exports和module.expors之间有什么区别及联络?的细致内容,更多请关注 百分百源码网 其它相干文章!