如何在JavaScript中从模块中导出variables?
根据这篇文章,我们知道variables可以从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
。 你能帮我弄清楚这个原因吗?
UPDATE1
我已经更新了上面的代码:
// 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稍后才会出现
如果你init()
在controller.js它应该工作。
我通过testing发现的另一个问题。
当你做MSG = {t: 12};
在init()
,你用新的对象覆盖了MSG
,但是这并不影响handler.MSG
的引用。 你需要直接设置MSG.t = 12;
,或者修改 MSG
: MSG.t = 12;
。