针对问题做的自我总结:
在node里,js的顶层对象是global; 在global上定义的属性和函数,在任何模块里都可以访问;
这样的写法,fruit就成为global对象上定义的属性,其它模块可以通过 fruit 或 global.fruit 访问到:
fruit = "apple";
.
这两种写法是等效的 this === exports; 这时的fruit就成为模块对象exports上的属性:
this.fruit = "apple";
exports.fruit = "apple";
.
定义局部变量:
var fruit = "apple";
.
如果是在test.js模块内调用test(), 则this === global:
fruit = "banana"; //必须这样定义, 相当于: global.fruit;
function test(){
console.log("fruit: ", this.fruit); //则this === global;
}
test();
.
如果是在另外一个模块内,调用test.js 内的test方法,则其使用的是对象module.exports, 所以 this === exports:
this.fruit = "orange";
function test(){
console.log("fruit: ", this.fruit); //this === exports;
}
exports.test = test;
这样外部模块即可以访问到 test函数又可以访问到fruit属性。
所以,实际使用时应该使用局部变量,外部模块只能通过方法来访问内部变量:
var fruit = "apple";
function test(){
console.log("fruit: ", fruit);
}
exports.test = test;