如何从 JavaScript 中的模块导出变量?

How to export a variable from a module in JavaScript?

据此post我们知道可以从JavaScript中的一个模块导出变量:

// module.js
(function(handler) {
  var MSG = {};

  handler.init = init;
  handler.MSG = MSG;

  function init() {
    // do initialization on MSG here
    MSG = ...
  }
})(module.exports);

// app.js
require('controller');
require('module').init();

// controller.js
net = require('module');

console.log(net.MSG); // output: empty object {}

以上代码在 Node.js 中,我在 controller.js 中得到一个 empty object。能帮我看看这是什么原因吗?

更新1

我更新了上面的代码:

// module.js
(function(handler) {
  // MSG is local global variable, it can be used other functions
  var MSG = {};

  handler.init = init;
  handler.MSG = MSG;

  function init(config) {
    // do initialization on MSG through config here
    MSG = new NEWOBJ(config);
    console.log('init is invoking...');
  }
})(module.exports);

// app.js
require('./module').init();
require('./controller');

// controller.js
net = require('./module');
net.init();
console.log(net.MSG); // output: still empty object {}

输出:仍然是空对象。为什么?

当您 console.log(net.MSG) 在 controller.js 时,您还没有调用 init()。那只会在 app.js.

之后出现

如果您 init() 在 controller.js 中,它应该可以工作。


我通过测试发现的另一个问题。

当您在 init() 中执行 MSG = {t: 12}; 时,您会用新对象覆盖 MSG,但这不会影响 handler.MSG 的引用。你需要直接设置handler.MSG,或者修改 MSG: MSG.t = 12;.