【问题标题】:How to export a variable from a module in JavaScript?如何从 JavaScript 中的模块导出变量?
【发布时间】:2015-05-06 09:06:44
【问题描述】:

根据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 {}

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

【问题讨论】:

  • 您正在覆盖局部变量,而不是 handler 属性。如果必须,请分配给hander.MSG,但最好只扩展现有对象。

标签: javascript node.js variables module


【解决方案1】:

当你在controller.js 中console.log(net.MSG) 时,你还没有调用init()。这只会在 app.js 中稍后出现。

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


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

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

【讨论】:

  • 我找到了另一个原因。已编辑。
猜你喜欢
  • 2022-07-11
  • 1970-01-01
  • 1970-01-01
  • 2021-02-13
  • 2022-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多