javascript - Node.js pass variable to module vs pass variable to every module function -
i'm learning node.js , interested in there difference between following 2 cases. i.e. have variable myvar
(like db connection or constant string "test") needed passed in many modules , submodules.
first case. create modules, accept variable param:
submodule.js:
var option , submodule = {}; submodule.func = function(){ ... var = option; ... } module.exports = function(opts){ option = opts; return submodule; }
module1.js:
var option , submodule , module1 = {}; module1.func = function(){ ... submodule.func(); ... var = option; ... } module.exports = function(opts){ option = opts; submodule = require('./submodule')(opts); return module1; }
in case if submodule used in several modules same myvar
value (i.e. 2 modules) submodule's module.exports
function called 2 times. in node.js mans said "modules cached after first time loaded". , can't understand module cached or not.
another case: myvar
can passed parameter module functions. code like:
submodule.js:
function func(option){ ... var = option; ... }; exports.func = func;
module1.js:
var submodule = require('./submodule'); function func(option){ ... submodule.func(option); ... var = option; ... }; exports.func = func;
so question is: there difference between 2 cases or same?
i'm not sure you're asking here, if need pass values modules should make sure export functions accept parameters. when module cached, means module initialized once. think of module object:
var = 1; var b = 2; console.log("init!"); module.exports.test = function(){ console.log("this function!"); }
here, a, b, , first log run once. when module requested , cached. when
var example = require("module")
if never created it'll initialize a, b, , log message. if created give reference exported. each time call:
example.test()
it output: this function!
but not a, b, , first log run again.
think of statements not exported private static variables of object.
here working example:
app.js
var s = require("./sample"); var y = require("./sample"); s.test(); y.test(); s.test(); console.log("finished");
sample.js
var = 1; var b = 2; console.log("init!"); function test() { console.log("here! " + a); a++; } exports.test = test;
this outputs:
init! here! 1 here! 2 here! 3 finished
does @ all?
Comments
Post a Comment