Node.js 中的模块范围
Module scope in Node.js
我很难弄清楚以下模块作用域在 node.js 中是如何工作的。
main.js
module.exports = App = {
add: function(a, b) {
return a + b;
}
}
var getNumber = require('./module');
var result = App.add(100, getNumber());
module.js
var number = 200;
module.exports = function () {
console.log(App); // App is visible here - how come?
return number;
};
我想知道为什么App在模块中是可见的,因为它不是必需的。如果我不再导出App,它是不可见的。
由于您没有声明 var App
,App
隐式成为全局变量。即使您根本没有 module.exports
,也会发生这种情况。
App
在全局范围内:
foo = {}
foo.bar = baz = 5
console.log(baz)
// baz is available on the global scope
我很难弄清楚以下模块作用域在 node.js 中是如何工作的。
main.js
module.exports = App = {
add: function(a, b) {
return a + b;
}
}
var getNumber = require('./module');
var result = App.add(100, getNumber());
module.js
var number = 200;
module.exports = function () {
console.log(App); // App is visible here - how come?
return number;
};
我想知道为什么App在模块中是可见的,因为它不是必需的。如果我不再导出App,它是不可见的。
由于您没有声明 var App
,App
隐式成为全局变量。即使您根本没有 module.exports
,也会发生这种情况。
App
在全局范围内:
foo = {}
foo.bar = baz = 5
console.log(baz)
// baz is available on the global scope