CommonJS规范规定,每个模块内部,module变量代表当前模块。这个变量是一个对象,它的exports属性(即module.exports)是对外的接口。加载某个模块,其实是加载该模块的module.exports属性。为了方便,Node为每个模块提供一个exports变量,指向module.exports。这等同在每个模块头部,有一行这样的命令。
var exports = module.exports;
同时,在该模块中,this也指向exports:
console.log(exports === module.exports); //true
console.log(this === exports); //true
console.log(this === module.exports); //true
我们再说一下Node中this指向的问题,这一点和JS中不太一样,在函数中,this指向的是global对象:
function test1(){
console.log(this);
}
test1()
在构造函数中this指向的是它的实例,而不是global。
function test1(){
this.name = 'jack';
}
let foo = new test1()
console.log(foo);
console.log(global.name);
而在全局中,this指向的是一个空对象,与module.exports挂钩。
这就意味着我们可以在exports和this对象上添加方法,同样可以让其对外输出,就如同在module上添加一样。
// 01.js中:
var x = 5;
var addX = function (value) {
return value + x;
};
exports.x = x;
module.exports.addX = addX;
this.y = 777
// 02.js中:
const test = require("./01")
console.log(test);
输出:
但是由于Node模块是通过module.exports导出的,所以如果我们将exports或者module.exports直接指向一个值,就会切断exports和module。exports之间的联系:
// 01.js中:
var x = 5;
var addX = function (value) {
return value + x;
};
exports = x; //直接给exports赋值
module.exports.addX = addX;
this.y = 777
输出:
exports无法导出,但是不影响this的导出。
// 01.js中:
var x = 5;
var addX = function (value) {
return value + x;
};
exports.x = x;
module.exports = addX; //直接给module.exports赋值
this.y = 777
输出:
以module.exports的导出为主,直接切断了exports和this对外导出的接口。