转:细说exports和module.exports

细说一:
exports和module.exports的做用都是把文件模块里的方法和属性暴露给require返回的对象(模块对象)进行调用。可是,二者之间存在着本质区别,exports的属性和方法均可以被module.exports替代。例以下面代码:数组

export.myName = 'Pandora_Galen'; 和 module.exports.myName = 'Pandora_Galen'; // 做用是同样的
1
可是,exports不能替代module.exports方法,能够被理解为包含关系。app

全部的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对象
1
2
3
4
5
执行后输出:ui

{ name: 'a', happy: [Function] }
1
从结果上看module.exports至关于require所返回的对象。也就是说全部require返回的对象实质上和module.exports对象是相同的。.net

细说二:
module.exports方法还能够单独返回一个数据类型,而exports返回的只能是一个对象。对象

因此,当咱们须要返回一个数组、字符串、数字等类型时,就必须使用module.exports了。blog

细说三:
当使用了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');
};get

console.log( module.exports ); // 打印module.exports对象
1
2
3
4
5
6
7
8
9
建立执行上面文件模块的执行文件app.js , 代码以下:

var Book = require('./test.js');
console.log( Book );
console.log( Book.name );
console.log( Book.getName() );
1
2
3
4
运行app.jswen文件,执行结果以下:

test for modules.exports ignore! // 由打印console.log( module.exports)而来test for modules.exports ignore! // 由打印console.log( Book )而来undefined // 由打印console.log( Book.name )而来--------------------- 做者:Dragon_GL 来源:CSDN 原文:https://blog.csdn.net/u014695532/article/details/51154295 版权声明:本文为博主原创文章,转载请附上博文连接!

相关文章
相关标签/搜索