节点.js中的模块范围

Module scope in Node.js

本文关键字:模块 范围 js 节点      更新时间:2023-09-26

我很难弄清楚以下模块范围如何在node.js中工作。

主.js

module.exports = App = {
  add: function(a, b) {
    return a + b;
  }
}
var getNumber = require('./module');
var result = App.add(100, getNumber());

模块.js

var number = 200;
module.exports = function () {
  console.log(App); // App is visible here - how come?
  return number;
};

我想知道为什么应用程序在模块中可见,因为它不是必需的。如果我不再导出应用程序,它将不可见。

由于您没有声明var AppApp隐式地成为全局变量。即使您根本没有module.exports,也会发生这种情况。

App在全局范围内:

foo = {}
foo.bar = baz = 5
console.log(baz)
// baz is available on the global scope