内容简介:Node.js 模块里,我们经常见着来新建一个然后在命令行下运行
既生瑜,何生亮
Node.js 模块里,我们经常见着 module.exports
与 exports
。二者区别在哪?
来新建一个 module.js
文件:
console.log(exports === module.exports); console.log(exports);
然后在命令行下运行 node module.js
:
$ node module.js
true
{}
===
判断结果为 true
。这说明二者是一样的,指向同一个空对象 {}
。
那,什么时候只能用 module.exports
?什么时候只能用 exports
?从 模块编写者
的角度出发,并没有什么区别,二者都能用;若非要说个区别,大概是 exports
比 module.exports
少打 7 个字符,省点时间:
exports.pi = 3.14 // vs module.exports.pi = 3.14
但是从模块使用者角度说,则二者是有区别的。
不具名数据
假设我作为模块使用者,要在我的代码中导入一个函数:
const func = require('./module');
则编写者只能使用 module.exports
来定义:
module.exports = function () {}
如果编写者使用 exports
来定义:
exports.func = function () {}
则使用者必须知道该函数的名称才能使用:
const { func } = require('./module');
把函数换成变量、常量或其它,也是一样道理。
以上所述就是小编给大家介绍的《区别 module.exports 与 exports》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Developing Large Web Applications
Kyle Loudon / Yahoo Press / 2010-3-15 / USD 34.99
As web applications grow, so do the challenges. These applications need to live up to demanding performance requirements, and be reliable around the clock every day of the year. And they need to withs......一起来看看 《Developing Large Web Applications》 这本书的介绍吧!