版权声明:转载请注明:http://blog.csdn.net/update7?viewmode=contents https://blog.csdn.net/update7/article/details/86992209
exports 和 module.exports 的区别(exports是module.exports的一个引用)
-
每个模块中都有一个 module 对象
-
module 对象中有一个 exports 对象
-
我们可以把需要导出的成员都挂载到 module.exports 接口对象中
-
也就是:
moudle.exports.xxx = xxx
的方式 -
但是每次都
moudle.exports.xxx = xxx
很麻烦,点儿的太多了 -
所以 Node 为了你方便,同时在每一个模块中都提供了一个成员叫:
exports
-
exports === module.exports
结果为true
s -
所以对于:
moudle.exports.xxx = xxx
的方式 完全可以:expots.xxx = xxx
-
当一个模块需要导出单个成员的时候,这个时候必须使用:
module.exports = xxx
的方式 -
不要使用
exports = xxx
不管用 -
因为每个模块最终向外
return
的是module.exports
-
而
exports
只是module.exports
的一个引用 -
所以即便你为
exports = xx
重新赋值,也不会影响module.exports
-
但是有一种赋值方式比较特殊:
exports = module.exports
这个用来重新建立引用关系的
foo.js
var foo = 'bar'
function add(x, y) {
return x + y
}
// 这种方式不行。
// exports = add
// 如果一个模块需要直接导出某个成员,而非挂载的方式
// 那这个时候必须使用下面这种方式
module.exports = 'hello'
module.exports = function (x, y) {
return x + y
}
module.exports = {
add: function () {
return x + y
},
str: 'hello'
}
// 你可以认为在每个模块的最后 return 了这个 exports
// 只能得到我想要给你的成员
// 这样做的目的是为了解决变量命名冲突的问题
// exports.add = add
// exports 是一个对象
// 我们可以通过多次为这个对象添加成员实现对外导出多个内部成员
// exports.str = 'hello'
// 现在我有一个需求:
// 我希望加载得到直接就是一个:
// 方法
// 字符串
// 数字
// 数组
main.js
// 默认得到的是对象
// 使用对象中的成员必须 . 点儿某个成员来访问
// 有时候,对于一个模块,我仅仅就是希望导出一个方法就可以了
var fooExports = require('./foo')
// ReferenceError: foo is not defined
// console.log(foo)
console.log(fooExports)