再讲之前先简单说下node加载模块机制.
这里先提供一个简单模块
// hello.js 模块
function a() {};
module.exports = a;
// node执行前会先准备一个 module 变量:
const module = {
id: 'hello.js',
exports: {},
...
}
// node 会将 hello 模块放入一个包装函数中,利用闭包开辟单独作用域
const load = function (exports, module) {
// hello.js 文件内容
...
// load 函数返回,返回 module.exports
return module.exports;
}
// 调用load函数,将 module.exports 传入,所以在 load 函数中 exports 就是 module.exports 一个引用.
const exported = load(module.exports, module);
// node 将此模块保存起来,使用 require 引用是,就会从内存中找到对应的该模块读取.
save(module, exported);
弄明白上面执行机制,应该就理解exports、module.exports 那些事了.
exports 是 module.exports 一个引用, 也就是说:
// 这两句代码意思是一样的
exports.a = a;
module.exports.a = a;
为什么 exports = a 有问题呢?
exports 是一个引用类型,这样写,只是让exports 指向 a,require 引用时,使用的任然是 module.exports 这片区域, 还是 {};