nodejs中exports和module.exports

671 查看

我是看七天学会NodeJS 入的坑. 结果被一同事给问住了. exports和module.exports有啥区别.作为一新手.根本没搞清楚. 一翻测试得到了如下的结论

exports = module.exports
不过别急.里面有好多有意思的东西

首先.nodejs启动后,会为每个加载的js文件会产生一个module对象(此处待验证因为没仔细找相关文档,只是目测结果)

app.js文件代码:

console.log(module)

输出:

{ id: '.',
exports: {},
parent: null,
filename: 'E:\\node\\test\\app.js',
loaded: false,
children: [],
paths:
[ 'E:\\node\\test\\node_modules',
'E:\\node\\node_modules',
'E:\\node\\node\\node_modules',
'E:\\node\\node_modules',
'E:\\node_modules' ] }

这是app.js文件输出的module对象, 相信对大家.应该都能猜到里面各个参数的意思.但对新手来说. exports 确是个深深的坑.
我们来修改下app.js

var foo = require("./foo");

新建foo.js

module.exports.hello = 'bbb'
console.log(exports.hello)
exports.hello = 'aaa'
console.log(module.exports.hello)

输出:

bbb
aaa

哎哟 我们操作是同个东西吗. 没错.这就是开篇的那个结论. 但接下来. 有意思的东西. 继续改
app.js

var foo = require("./foo");
console.log(foo);

foo.js

var View = function (){}
View.prototype.test = function(){
console.log('test')
}
View.test1 = function(){
console.log('test1')
}
exports = View;

我预期它会给我输出View这个function对象 (因为我javascript很矬所以预期错了.) 结果返回了 {}

怎么了?没怎么.理解彻底错了呗. 继续改:
app.js

....
console.log(foo.view);

foo.js

....
exports.view = View;

终于正常输出了. 好像明白什么了. require 真正返回的是module的exports属性. 而 单纯foo.js中的exports 只不过是module的exports属性的引用 . 直接对exports赋值.对module是没有任何改变的.当然不会正常输出. 这就完了吗? 没有. 下面算是语法分析了. foo.js再改 我要给我导出的对象用exports加点属性

....
// exports.view = View;
module.exports =  View;
exports = function  (argument) {
    // body...
}

结果. 它还真xxx了. 我的xxx属性呢.

{ [Function] test1: [Function] }

唉.这次真的是硬伤问题了. module.exports = View 这不是也改了 module的exports 而 exports还是指向原来的那个{}

所以foo.js的正确姿势

....
exports = module.exports =  View;
exports.xxx= function  (argument) {
    // body...
}