细说exports和module.exports
来源:互联网 发布:局域网共享端口开启 编辑:程序博客网 时间:2024/06/05 19:27
细说一:
exports和module.exports的作用都是把文件模块里的方法和属性暴露给require返回的对象(模块对象)进行调用。但是,两者之间存在着本质区别,exports的属性和方法都可以被module.exports替代。例如下面代码:
export.myName = 'Pandora_Galen'; 和 module.exports.myName = 'Pandora_Galen'; // 作用是一样的
但是,exports不能替代module.exports方法,可以被理解为包含关系。
所有的exports对象最终都是通过module.exports传递执行的。因此,可以说exports是给module.exports添加属性和方法(我有时在想,exports可不可以被看做是对module.exports的一个引用)。下面的代码是用来验证我们在这里的说法的:
exports.name = 'a'; // 暴露name属性exports.happy = function () { // 暴露happy方法 console.log('mm');};console.log( module.exports ); // 打印module.exports对象
执行后输出:
{ name: 'a', happy: [Function] }
从结果上看module.exports相当于require所返回的对象。也就是说所有require返回的对象实质上和module.exports对象是相同的。
细说二:
module.exports方法还可以单独返回一个数据类型,而exports返回的只能是一个对象。
所以,当我们需要返回一个数组、字符串、数字等类型时,就必须使用module.exports了。
细说三:
当使用了module.exports关键词以后,该模块中的所有exports对象执行的属性和方法都将被忽略。例如下面代码片段test.js(文件模块名):
module.exports = ' test for module.exports ignore! '; // 返回一个字符串exports.name = 'Galen';/* 定义getName函数,并暴露给外部接口 */exports.getName = function() { console.log('My name is Galen');};console.log( module.exports ); // 打印module.exports对象
创建执行上面文件模块的执行文件app.js , 代码如下:
var Book = require('./test.js');console.log( Book );console.log( Book.name );console.log( Book.getName() );
运行app.jswen文件,执行结果如下:
test for modules.exports ignore! // 由打印console.log( module.exports)而来test for modules.exports ignore! // 由打印console.log( Book )而来undefined // 由打印console.log( Book.name )而来
1 0
- 细说exports和module.exports
- exports 和module.exports
- exports和module.exports
- exports和module.exports
- exports 和 module.exports
- module.exports和exports
- module.exports和exports
- [nodejs]exports和module.exports
- Node.j: exports 和 module.exports
- exports 和 module.exports 的区别
- [前端] exports 和 module.exports 的区别
- exports 和 module.exports 的区别
- nodejs exports和module.exports区别
- exports 和 module.exports 的区别
- nodejs中module.exports和exports比较
- nodejs exports和module.exports的区别
- exports 和 module.exports 的区别
- exports 和 module.exports 的区别
- 汉诺塔问题
- 最长公共子序列
- json使用总结
- ActiveX(MFC)控件——添加接口及WEB调用
- oracle中实现截取字符串(substr)、查找字符串位置(instr)、替换字符串(replace)
- 细说exports和module.exports
- CentOS 6.5环境下heartbeat高可用集群的实现及工作原理详解
- Android 5.0 Notification的改变
- struts1 action 之间的跳转
- JDK容器与并发—Map—TreeMap
- Python 爬虫学习1
- JAVA集合类图
- 基于稀疏三维变换域协同滤波的图像降噪
- centos下configure zeromq-4.1.2时错误解决方法