【发布时间】: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