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”;

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.

Software for news and media and civic tech. Cat herder. Director at Glitch Digital.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store