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

标签 javascript node.js variables module

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

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

最佳答案

当你在 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;

关于javascript - 如何从 JavaScript 中的模块导出变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30072248/

相关文章:

java - 从类的实例变量创建数组

javascript - 创建直方图函数

javascript - 在 JavaScript GET 查询中发送 SSL 证书

javascript - Node.js - 如果我在 I/O 和回调仍在运行时调用 response.end 会发生什么?

node.js - typescript |无法安装类型脚本

matlab - 如何在matlab中更新变量?

javascript - 从 google maps api json 获取 formatted_address

javascript - jquery: fadeOut().empty().append(...).fadeIn() 只有第一次不能正常工作

javascript - 突出显示单个单元格

mysql、@variable 和 if 语句