module.exports 和 exports的区别
来源:互联网 发布:网站统计分析系统源码 编辑:程序博客网 时间:2024/06/05 04:12
通常来讲, 我们在node模块中输出变量有两种方法.
例一. 采用module.exports
function hello() { console.log('Hello, world!');}function world(name) { console.log('Hello, ' + name);}module.exports = { hello: hello, world: world};
例二. 采用exports
function hello() { console.log('Hello, world!');}function world(name) { console.log('Hello, ' + name);}exports.hello = hello;exports.world= world;
区别
不可以直接对进行exports赋值:
exports = { hello: hello, world: world};//这样代码不报错, 但是没有用, 接口并未暴露出来. 原因请看下面
原因
首先,Node会把整个待加载的 .js文件放入一个包装函数load中执行。在执行这个load()函数前,Node事先准备好了module对象. module中有一个空的exports方法.
var load = function (exports, module) { // .js的文件内容 ... // load函数返回: return module.exports;};var exported = load(module.exports, module);
那么为什么在自己的 .js 文件中写成exports = { … }会没有效果呢 ?
系统自动给nodejs 文件增加2个变量 exports 和 module, module 又有一个属性 exports, 这个exports 属性指向一个空对象 {}; 同时 exports这个变量也指向了这个空对象{};
于是就有了 exports => {} <=module.exports.
这2个exports 其实是没有直接关系的,唯一的关系是: 他们初始都指向同一个空对象{};
如果其中一个不指向做个空对象了, 那么他们的关系就没有了. 因此也就没有任何效果了.
总结
因此如果是想要键值对象的这种格式, exports.text = …; 是可以的.
但如果是一个数组或者是函数. 只有module.exports = function(){ }有效.
因此, 不论任何时候都推荐用module.exports
阅读全文
0 0
- exports 和 module.exports 的区别
- [前端] exports 和 module.exports 的区别
- exports 和 module.exports 的区别
- exports 和 module.exports 的区别
- nodejs exports和module.exports的区别
- exports 和 module.exports 的区别
- exports 和 module.exports 的区别
- module.exports和exports的区别
- exports 和 module.exports 的区别
- exports 和 module.exports 的区别
- exports 和 module.exports 的区别
- exports 和 module.exports 的区别
- exports和module.exports的区别
- exports 和 module.exports 的区别
- exports 和 module.exports 的区别
- exports 和 module.exports 的区别
- exports 和 module.exports 的区别
- exports 和 module.exports 的区别
- UVA--- 11183 【有定根的有向图的最小生成树-裸最小树形图】
- HTTP
- 安装Ubuntu 14.10后要做的事(下)—— 开发工具篇
- 定时静音助手
- 【LeetCode】128. Longest Consecutive Sequence
- module.exports 和 exports的区别
- jsp中el表达式的使用(fn标签的使用)
- C++入门知识
- nginx的虚拟主机配置和反向代理,负载均衡
- 安装Ubuntu 14.10后要做的事(上)—— 基础软件篇
- mysql 数据库中varchar的长度与字节,字符串的关系
- inline关键字和宏函数的异同
- HBase之api的基本运用(三)
- Apache ActiveMQ Cluster Master and Slave with JDBC