Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
228 views
Welcome To Ask or Share your Answers For Others

1 Answer

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...