0

This is probably a dumb question but i wanted to clarify this things to my self and get other opinions about it.

Let's say i have a node file x.js like this.

var x=0;
module.exports = init = function(someValue){
     if(someValue)
        x=someValue;
}
init.prototype.getX = function(){
    return x;
}

And let's say i've y.js like this.

var X = require('x')(10);
X.getX() //this will return 10 right?

But my question is this, if i have z.js file with the following content.

var X = require('x')();
//what will x.getX(); returns?

do it return 10, because 10 is set on y.js file or 0?

In what way should i write the code to make it singleton across files(without database if it is possible)?

miqe
  • 3,209
  • 2
  • 28
  • 36

1 Answers1

1

Node JS cache modules so everytime same module will be loaded as node JS already wraps all the modules in singletons.

So, yes z.js will return 10 provided you have already loaded y.js

If you really want to use singleton( why not dependency injection) then this is a good way to go.

Update : As I see you are exporting constructor, so you will have to use new keyword, changing your y.js to

var X = require('x')(10);
var instanceOfX = new X();
instanceOfX.getX() //this will return 10 definitely and focus on new operator

and update z.js similarly

Community
  • 1
  • 1
bugwheels94
  • 30,681
  • 3
  • 39
  • 60
  • i think it should be something like this `var X = require('x'); var x = new X();` then `x.getX()` . update your answer accordingly and i'll accept is as an answer – miqe Dec 13 '16 at 16:28
  • Thanks for the answer it was really helpful. – miqe Dec 13 '16 at 17:30