user3025492
user3025492

Reputation: 3043

How can I share an object between my modules?

So I have a helper module H, which I require from my main script M:

M.js:

var o = {foo: 'bar'};
require('H.js').doFunc();

H.js:

module.exports = {doFunc: function(){ /* how can I set X to o.foo in M's scope? */ return X; }};

Thus one can expose things in this direction. What can I do to share things back the other way?

Upvotes: 0

Views: 111

Answers (3)

M.js

var o = {foo: 'bar'};
require('H.js')(o);

H.js

module.exports = function (o) {
   console.log(o);
}

Upvotes: 0

user3025492
user3025492

Reputation: 3043

M:

o = {foo: 'bar'};

require('./H.js')(); // 'bar'

H:

module.exports = o.foo;

By not declaring the variable, it gets stored on the global object which is shared.

Upvotes: 0

slebetman
slebetman

Reputation: 113896

You can't quite do it the way you intend because node's architecture creates separate, individual global objects per module. However, you can get something similar using the mechanics of how this works in javascript.

In plain js, given:

function doFunc () {
    return this.foo;
}

var o = {foo:'bar'};

You can do:

o.dofunc = doFunc;
o.doFunc(); // returns 'bar'

Alternatively:

doFunc.call(o); // also returns 'bar'

So, applying this technique to modules:

In H.js:

module.exports.doFunc = function () {return this.foo}

In M.js:

var o = {
    foo: 'bar',
    dofunc : require('H.js').doFunc
};
o.dofunc();

Upvotes: 1

Related Questions