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