在nodejs中是通过module.exports导出模块,每个文件都有一个module对象,其中有一个成员对象exports,如下:
modeule.exports = {
exports : {
}
}
return module.exports;
所以最后导出的是module.exports
而exports只是module.exports的一个引用,
相当与在页面开始有这样一行代码:
let exports = module.exports;
所以在导出页面数据成员时可以有如下导出方法:
//导出单个成员
module.exports = 'hello'
//或
module.exports = {
foo: "bar"
}
上面这种方式可以直接得到当前模块导出的成员变量,不需要使用'.'访问,
但是一个页面只能有一个module.exports直接赋值,否则后面的会覆盖前面的
//导出多个成员
exports.add = function() {}
exports.foo = function() {}
exports.bar = 'hello';
//或者
module.exports = {
add: function() {},
foo: "bar"
}
//或者
module.exports.add = function() {}
module.exports.foo = function() {}
module.exports.bar = 'hello';
注意点:不能直接给exports赋值,会断开它对module.exports的引用
当给module.exports赋值的时候,之后通过exports挂载成员变量也不会起作用
除非再次添加引用:exports = module.exports之后