您的位置:首页 > Web前端 > Node.js

nodejs中module.exports和exports比较

2015-08-13 22:21 701 查看
首先定义一个module为math.js,在test.js中引用此module.

一下为通过几个使用情景来阐述其中的不同:

1.正常情况下,定义和使用module中的实例.

math.js:

exports.add=function(arg1,arg2){
return arg1+arg2;
};
exports.minus=function(arg1,arg2){
return arg1-arg2;
};
console.log(module);


test.js:

var math=require('./math.js');
console.log('math:'+math);
console.log(math.add(3,4));
console.log(math.minus(5,3));


控制台中信息:

module:

{ id: '/home/chander-zhang/NodeJS/test/math.js',
exports: { add: [Function], minus: [Function] },
parent:
{ ... },
filename: '/home/chander-zhang/NodeJS/test/math.js',
loaded: false,
children: [],
paths:
[ '/home/chander-zhang/NodeJS/test/node_modules',
'/home/chander-zhang/NodeJS/node_modules',
'/home/chander-zhang/node_modules',
'/home/node_modules',
'/node_modules' ] }


math:

[object Object]


此时math是一个对象.

2.

math.js:

exports.add=function(arg1,arg2){
return arg1+arg2;
};
minus=function(arg1,arg2){
return arg1-arg2;
};
module.exports=minus;
console.log(module);


test.js:

var math=require('./math.js');
console.log('math:'+math);
//console.log(math.add(3,4));
console.log(math(5,3));  //相当于执行了 minus(5,3).


控制台中信息:

module:

{ id: '/home/chander-zhang/NodeJS/test/math.js',
exports: [Function],
parent:
{ ... },
filename: '/home/chander-zhang/NodeJS/test/math.js',
loaded: false,
children: [],
paths:
[ '/home/chander-zhang/NodeJS/test/node_modules',
'/home/chander-zhang/NodeJS/node_modules',
'/home/chander-zhang/node_modules',
'/home/node_modules',
'/node_modules' ] }


math:

function (arg1,arg2){
return arg1-arg2;
}


如果使用
math.add()
math.minus()
将会出错,因为此时math是一个函数.

即便module中出现了
exports.add
,由于为
module.exports
赋了值,也不能使用
math.add()
.

3.

math.js:

add=function(arg1,arg2){
return arg1+arg2;
};
minus=function(arg1,arg2){
return arg1-arg2;
};
module.exports=add;
module.exports=minus;
console.log(module);


此时执行tes.js的情况和(2)中相同.如果module中出现多个module.exports,那最后一个会将前面的全部覆盖掉.所以math依旧是:

function (arg1,arg2){
return arg1-arg2;
}


总结:可以将module.exports和exports看作两个普通的变量,在初始没有赋值的情况下它们指向的是同一对象.在使用require()时,只会传递module.exports中的对象.所以即便两个变量都赋值,也不会使用exports所指的对象.

参考:(https://cnodejs.org/topic/54e67b70629934692ea99f91)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  exports moduel-exp