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

时间:2023-01-24 23:07:22

According to this post we know that variables can be exported from one module in JavaScript:

根据这篇文章我们知道变量可以从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 {}

Those above codes are in Node.js and I get one empty object in my controller.js. Could you please help me figure out the reason of this?

上面的代码在Node.js中,我在controller.js中得到一个空对象。你能帮我弄清楚这个的原因吗?

Update1

I have updated the above codes:

我已更新上述代码:

// 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 {}

Output: still empty object. Why?

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

1 个解决方案

#1


When you console.log(net.MSG) in controller.js, you have not yet called init(). That only comes later in app.js.

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

If you init() in controller.js it should work.

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


Another issue i discovered through testing.

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

When you do MSG = {t: 12}; in init(), you overwrite MSG with a new object, but that doesn't affect handler.MSG's reference. You need to either set handler.MSG directly, or modify MSG: MSG.t = 12;.

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

#1


When you console.log(net.MSG) in controller.js, you have not yet called init(). That only comes later in app.js.

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

If you init() in controller.js it should work.

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


Another issue i discovered through testing.

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

When you do MSG = {t: 12}; in init(), you overwrite MSG with a new object, but that doesn't affect handler.MSG's reference. You need to either set handler.MSG directly, or modify MSG: MSG.t = 12;.

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