2

According to this post we know that variables can be exported from one module in 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?

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?

Community
  • 1
  • 1
zangw
  • 43,869
  • 19
  • 177
  • 214
  • 1
    You are overwriting the local variable, not the `handler` property. If you must, do assign to `hander.MSG`, but it would be better to just extend the existing object. – Bergi May 07 '15 at 04:12

1 Answers1

1

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

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


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;.

Scimonster
  • 32,893
  • 9
  • 77
  • 89