node.js的模块中,定义本模块的导出是可以按如下两种方式进行:
1、直接使用exports对象进行操作,例如
exports.sayHello = function(name){
console.log("Hello,%s",name);
}
?2、稍微复杂一点,使用module.exports对象进行操作,写法为
module.exports.sayHello = function(name){
console.log("Hello,%s",name);
}
?这两种方式在这种情况下,效果是一致,都是在本模块中导出一个sayHello函数。但是这两种方式还是有一些区别的,module是本模块的引用,是模块引用,而exports对象只是模块内部的一个变量,是和module.exports指向同一个对象的引用。这种区别在下面的使用方式可以发现区别:
1、直接使用exports
function Examle(){
var name;
setName : function(newName){
name = newName;
},
sayHello = function(){
console.log("Hello,%s",name);
}
}
exports = Example;
?2、使用module.exports方式
function Examle(){
var name;
setName : function(newName){
name = newName;
},
sayHello = function(){
console.log("Hello,%s",name);
}
}
module.exports = Example;
?这两种方式的差距只是在最后导出的语句上,但是两种方式中,第一种并不能正常工作,应该使用第二种方式。
原因就是:exports只是module内部的一个引用变量,直接给exports赋值,只是让exports指向了其他地址空间,并没有影响module实际的导出对象的内容。
