Iain Collins
1 min readMar 3, 2017

--

Great question!

So if you do that and have a hello-world.js file that looks like this:

var HelloWorld = function() {
this.greeting=’Hello, World’;
};
var h = new HelloWorld();exports=module.exports=h;

And an index.js file that looks like this:

var helloWorldA = require(‘./hello-world’),
helloWorldB = require(‘./hello-world’),
helloWorldC = require(‘./hello-world’);
helloWorldB.greeting = “Hi”;
helloWorldC.greeting = “Hello again”;
console.log(helloWorldA.greeting);
console.log(helloWorldB.greeting);
console.log(helloWorldC.greeting);

What you’ll get is this:

$ node index.js
Hello again
Hello again
Hello again

…because it has the same problem of instances pointing to the same object.

Even though we created an new object in our library, any file that refers to that same library anywhere the project (whether that’s an index.js file or in some other library or in route that you are including) will still point to the same instance of it, because of the magic behind how require() works.

So, the creation of it as a new object needs to happen where we are using it.

--

--