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?

1
  • 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. Commented May 7, 2015 at 4:12

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

I found another reason. Edited.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.